一、Node后端实现

multer

  1. const express = require('express');
  2. const multer = require('multer');
  3. const app = express();
  4. const upload = multer({
  5. dest: 'c:/tmp'
  6. });
  7. // 单个文件的上传
  8. app.post('/upload', upload.single('avator'), (req, res) => {
  9. res.send(req.file);
  10. })
  11. // 多个文件的上传
  12. app.post('/uploadMany', upload.array('photos', 3), (req, res) => {
  13. res.send(req.files);
  14. })
  15. app.listen(3000);

二、前端代码

1. form表单文件上传

  1. <form action="/upload" method="POST" enctype="multipart/form-data">
  2. <input type="file" name="avatar" />
  3. <input type="submit" value="提交" />
  4. </form>

注意:enctype 属性, 它有三个可选值:
**

描述
application/x-www-form-urlencoded 在发送前编码所有字符(默认)
multipart/form-data 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
text/plain 空格转换为 “+” 加号,但不对特殊字符编码。

2. jquery ajax

  1. var formData = new FormData();
  2. formData.append('avatar', $('input[name="avatar"]')[0].files[0]);
  3. $.ajax({
  4. url: '/upload',
  5. type: 'POST',
  6. data: formData,
  7. processData: false, // 注意
  8. contentType: false, // 注意
  9. success: function () {
  10. }
  11. })

3. axios ajax

  1. var formData = new FormData();
  2. formData.append('avatar', $('input[name="avatar"]')[0].files[0]);
  3. axios.post('/upload', formData, {
  4. headers: {
  5. 'Content-Type': 'multipart/form-data'
  6. }
  7. })