如何使用 Axios 从表单发布文件 [英] How to post a file from a form with Axios

查看:29
本文介绍了如何使用 Axios 从表单发布文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

在烧瓶中:

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

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

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'
        }
    })
}

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

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

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

How can I get a file object sent via axios?

推荐答案

将文件添加到 formData 对象,并将 Content-Type 标头设置为 多部分/表单数据.

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'
    }
})

这篇关于如何使用 Axios 从表单发布文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆