Javascript 如何使用 Axios 从表单发布文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43013858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:36:17  来源:igfitidea点击:

How to post a file from a form with Axios

javascriptajaxfile-uploadaxios

提问by Don Smythe

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

当我使用以下命令将文件发布到烧瓶服务器时使用原始 HTML 我可以从烧瓶请求全局访问文件:

<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:

当我尝试对 Axios 执行相同操作时,flask 请求全局为空:

<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).

如果我使用上面相同的 uploadFile 函数,但从 axios.post 方法中删除标头 json,我会在我的 Flask 请求对象的表单键中获得一个字符串值的 csv 列表(文件是 .csv)。

How can I get a file object sent via axios?

如何获取通过 axios 发送的文件对象?

回答by Niklesh Raut

Add the file to a formDataobject, and set the Content-Typeheader to multipart/form-data.

将文件添加到formData对象,并将Content-Type标题设置为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'
    }
})

回答by maris

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

使用 Vue 的示例应用程序。需要在 localhost 上运行的后端服务器来处理请求:

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://codepen.io/pmarimuthu/pen/MqqaOE

回答by OCornejo

This works for me, I hope helps to someone.

这对我有用,我希望对某人有所帮助。

var frm = $('#frm');
let formData = new FormData(frm[0]);
axios.post('your-url', formData)
    .then(res => {
        console.log({res});
    }).catch(err => {
        console.error({err});
    });