代码之家  ›  专栏  ›  技术社区  ›  Komakino_1251

是否可以在JS中向单个Axios请求添加Body和and文件?

  •  0
  • Komakino_1251  · 技术社区  · 5 年前

    所以我可以用下面的POST请求发送一个文件或一个body,但是我如何将两者都发送呢?

    axios.post("http://localhost:3000/upload", formData )
    

    正文:{}

    服务器响应:

      files: {
            myFile: {
              name: 'close.bmp',
              data: <Buffer 42 4d 98 cb 01 00 00 00 00 00 36 00 00 00 28 00 00 00 c8 00 00 00 c4 00 00 00 01 00 18 00 00 00 00 00 62 cb 01 00 c3 0e 00 00 c3 0e 00 00 00 00 00 00 ... 117606 more bytes>,
              size: 117656,
              encoding: '7bit',
              tempFilePath: '',
              truncated: false,
              mimetype: 'image/bmp',
              md5: '8860ffe0891f5142164ea21b092c3996',
              mv: [Function: mv]
            }
          },
          body: {},
          route: Route {
            path: '/upload',
            stack: [ [Layer] ],
            methods: { post: true }
          },
          [Symbol(kCapture)]: false,
          [Symbol(RequestTimeout)]: undefined
        }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Jayce444    5 年前

    你可以很容易地做到这一点 express-fileupload . 因此,请安装它并让应用程序在您的节点服务器中使用它:

    import fileUpload from 'express-fileupload';
    
    app.use(fileUpload());
    

    FormData 对象并将文件和任何其他属性附加到其中:

    const upload = (file, description) => {
        const data = new FormData();
        data.append('file', file);
        data.append('description', description);
    
        return axios.post('/upload', data);
    };
    

    然后在您的路径中,您可以访问 files propery和其他 body

    function upload (req, res) {
        console.log(req.files);
        console.log(req.body.description);
        return res.status(200).end();
    }
    
    推荐文章