Interviewer: How to upload files? Tell me your thoughts

Interviewer: How to upload files? Tell me your thoughts

Insert image description here

1. What is file upload?

File upload is widely used in daily development. For example, the image upload function is used in operations such as posting on Weibo and WeChat Moments. Due to browser security restrictions, the browser cannot directly operate the file system. Therefore, it is necessary to access the file through the unified interface exposed by the browser, then read the file content into the specified memory, and perform the submit request operation to transfer the file into the memory. The file content is uploaded to the server, and the server parses the data information transmitted from the front end, and finally saves the file to the server's file system.

File upload requires setting the request header to content-type: multipart/form-data, which multipartindicates mixed resources on the Internet, that is, the resources are composed of multiple elements, and form-dataindicates that files can be uploaded using HTML Forms and POST methods.

The request structure for file upload is as follows:

POST /upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=--------------------------1234567890

--------------------------1234567890
Content-Disposition: form-data; name="file"; filename="example.jpg"
Content-Type: image/jpeg

... binary data of the image ...
--------------------------1234567890--

Among them, boundaryrepresents the separator, used to separate different form items. Each form item must contain Content-Dispositiona header; other header information is Content-Typeoptional.

2. How to upload files?

File upload can be divided into two steps:

  1. File upload
  2. File parsing

1. File upload

<input type="file">On the front end, we can implement the file upload form through HTML elements:

<form action="http://localhost:8080/api/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="file" value="" multiple="multiple" />
    <input type="submit" value="提交"/>
</form>

On the backend, we can use middleware in the Koa framework koa-bodyto parse the uploaded file data:

npm install koa-body
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();

app.use(koaBody({
    
    
    multipart: true,
    formidable: {
    
    
        maxFileSize: 200 * 1024 * 1024    // 设置上传文件大小最大限制,默认2M
    }
}));

app.use(async (ctx) => {
    
    
    // 获取上传的文件
    const file = ctx.request.files.file;
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    let filePath = path.join(__dirname, 'public/upload/') + `/${
      
      file.name}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
    ctx.body = "上传成功!";
});

app.listen(8080, () => {
    
    
    console.log('Server started on http://localhost:8080');
});

2. File analysis

On the server side, we need to parse the uploaded file and save it to the specified directory. In the above code, we fshandle the saving operation of the file by using modules.

In addition to using koa-body, we can also use koa-multermiddleware to implement file upload:

npm install koa-multer
const Koa = require('koa');
const Router = require('koa-router');
const multer = require('koa-multer');
const path = require('path');

const app = new Koa();
const router = new Router();

const storage = multer.diskStorage({
    
    
  destination: (req, file, cb) => {
    
    
    cb(null, "./upload/")
  },
  filename: (req, file, cb) => {
    
    
    cb(null, Date.now() + path.extname(file.originalname))
  }
})

const upload = 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');
});

In the above code, we use multermiddleware to implement file upload. storageThe option is used to set the save path and file name of the file, upload.single('file')indicating that only a single file is uploaded.

references

おすすめ

転載: blog.csdn.net/weixin_52898349/article/details/132826494