You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
POST /upload HTTP/1.1Host: example.comContent-Type: multipart/form-data; boundary=--------------------------1234567890--------------------------1234567890Content-Disposition: form-data; name="file"; filename="example.jpg"Content-Type: image/jpeg... binary data of the image ...--------------------------1234567890--
constKoa=require('koa');constRouter=require('koa-router');constmulter=require('koa-multer');constpath=require('path');constapp=newKoa();constrouter=newRouter();conststorage=multer.diskStorage({destination: (req,file,cb)=>{cb(null,"./upload/")},filename: (req,file,cb)=>{cb(null,Date.now()+path.extname(file.originalname))}})constupload=multer({
storage
});router.post("/upload",upload.single('file'),(ctx,next)=>{console.log(ctx.req.file);// 获取上传文件})app.use(router.routes());app.listen(8080,()=>{console.log('Server started on http://localhost:8080');});
面试官:如何实现文件上传?说说你的思路
一、什么是文件上传?
文件上传在日常开发中应用很广泛,比如在发微博、发微信朋友圈等操作中都会用到图片上传功能。由于浏览器的安全限制,浏览器不能直接操作文件系统,因此需要通过浏览器暴露出来的统一接口来访问文件,然后将文件内容读取到指定的内存中,并执行提交请求操作,将内存中的文件内容上传到服务端,服务端再解析前端传来的数据信息,最终将文件保存到服务器的文件系统中。
文件上传需要设置请求头为
content-type: multipart/form-data
,其中multipart
表示互联网上的混合资源,即资源由多种元素组成,而form-data
表示可以使用HTML Forms和POST方法上传文件。文件上传的请求结构如下:
其中,
boundary
表示分隔符,用于分隔不同的表单项。每个表单项必须包含Content-Disposition
头,其他头信息如Content-Type
为可选项。二、如何实现文件上传?
文件上传可以分为两个步骤:
1. 文件上传
在前端,我们可以通过HTML的
<input type="file">
元素来实现文件上传的表单:在后端,我们可以使用Koa框架中的
koa-body
中间件来解析上传的文件数据:2. 文件解析
在服务器端,我们需要将上传的文件进行解析,保存到指定的目录中。在上述代码中,我们通过使用
fs
模块来处理文件的保存操作。除了使用
koa-body
,我们还可以使用koa-multer
中间件来实现文件上传:以上代码中,我们使用
multer
中间件来实现文件上传,storage
选项用于设置文件的保存路径和文件名,upload.single('file')
表示只上传单个文件。参考文献
The text was updated successfully, but these errors were encountered: