How to post a file from a form with Axios

北城以北 提交于 2019-11-26 04:38:30

问题


Using raw HTML when I post a file to a flask server using the following I can access files from the flask request global:

<form id=\"uploadForm\" action=\'upload_file\' role=\"form\" method=\"post\" enctype=multipart/form-data>
    <input type=\"file\" id=\"file\" name=\"file\">
    <input type=submit value=Upload>
</form>

In flask:

def post(self):
    if \'file\' in request.files:
        ....

When I try to do the same with Axios the flask request global is empty:

<form id=\"uploadForm\" enctype=\"multipart/form-data\" v-on:change=\"uploadFile\">
<input type=\"file\" id=\"file\" name=\"file\">
</form>

uploadFile: function (event) {
    const file = event.target.files[0]
    axios.post(\'upload_file\', file, {
        headers: {
          \'Content-Type\': \'multipart/form-data\'
        }
    })
}

If I use the same uploadFile function above but remove the headers json from the axios.post method I get in the form key of my flask request object a csv list of string values (file is a .csv).

How can I get a file object sent via axios?


回答1:


Add the file to a formData object, and set the Content-Type header to multipart/form-data.

var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})



回答2:


Sample application using Vue. Requires a backend server running on localhost to process the request:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE



来源:https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!