axios post request to send form data

后端 未结 9 2443
走了就别回头了
走了就别回头了 2020-11-22 03:40

axios POST request is hitting the url on the controller but setting null values to my POJO class, when I go through developer tools in chrome, the payload conta

9条回答
  •  天命终不由人
    2020-11-22 04:13

    Upload (multiple) binary files

    Node.js

    Things become complicated when you want to post files via multipart/form-data, especially multiple binary files. Below is a working example:

    const FormData = require('form-data')
    const fs = require('fs')
    const path = require('path')
    
    const formData = new FormData()
    formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
    formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
    await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
      headers: formData.getHeaders()
    })
    
    • Instead of headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()
    • I use async and await above, you can change them to plain Promise statements if you don't like them
    • In order to add your own headers, you just headers: { ...yourHeaders, ...formData.getHeaders() }

    Newly added content below:

    Browser

    Browser's FormData is different from the NPM package 'form-data'. The following code works for me in browser:

    HTML:

    
    

    JavaScript:

    const formData = new FormData()
    
    // add a non-binary file
    formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')
    
    // add a binary file
    const element = document.getElementById('image')
    const file = element.files[0]
    formData.append('files[]', file, file.name)
    await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
    

提交回复
热议问题