axios post request to send form data

六眼飞鱼酱① 提交于 2019-11-26 10:15:16
Aaqib

You can post axios data by using FormData() like :

var bodyFormData = new FormData();

And then add the fields to the form you want to send :

bodyFormData.set('userName', 'Fred');

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile); 

And then you can use axios post method (You can amend it accordingly)

axios({
    method: 'post',
    url: 'myurl',
    data: bodyFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });

You can read more Here

cclient

Check out querystring.

You can use it as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

In my case I had to add the boundary to the header like the following:

const form = new FormData();
    formData.append(item.name, fs.createReadStream(pathToFile));

    const response = await axios({
        method: 'post',
        url: 'http://www.yourserver.com/upload',
        data: form,
        headers: {
        'content-type': `multipart/form-data; boundary=${form._boundary}`,
        },
    });

This solution is also useful if you're working with React Native.

Upload (multiple) binary files

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 concat = require('concat-stream')

const formData = new FormData()
formData.append('json', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('attachment', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
formData.pipe(concat({ encoding: 'buffer' }, async data => {
  const r = await rc.post('/restapi/v1.0/account/~/extension/~/fax', data, {
    headers: formData.getHeaders()
  })
  console.log(r.data)
}))
  • Instead of headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()
  • I need to use concat-stream to concat multiple file streams
  • I use async and await above, you can change them to plain Promise statements if you don't like them
thomasL

Even More straightforward:

axios.post('/addUser',{
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

The above method worked for me but since it was something I needed often, I used a basic method for flat object. Note, I was also using Vue and not REACT

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}

Which worked for me until I ran into more complex data structures with nested objects and files which then let to the following

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        objectToFormData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!