当我使用以下文件将文件发布到烧瓶服务器时使用原始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>
在烧瓶中:
def post(self):
if 'file' in request.files:
....
当我尝试对Axios执行相同操作时,求助栏请求全局为空:
<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,我会在我的flask请求对象的表单键中获得一个字符串值的csv列表(文件是.csv).
如何获取通过axios发送的文件对象?
解决方法:
将文件添加到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'
}
})
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!