使用原始HTML当我发布一个文件到flask服务器使用以下我可以从flask请求全局访问文件:
<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请求全局是空的:
<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中删除headers json。post方法我在我的flask请求对象的表单键中获得字符串值的csv列表(文件是.csv)。
如何通过axios获取文件对象?
对我来说,错误是我控制器中的实际参数名称……我花了好长时间才想明白,也许能帮到别人。我使用Next.js / .Net 6
客户:
export const test = async (event: any) => {
const token = useAuthStore.getState().token;
console.log(event + 'the event')
if (token) {
const formData = new FormData();
formData.append("img", event);
const res = await axios.post(baseUrl + '/products/uploadproductimage', formData, {
headers: {
'Authorization': `bearer ${token}`
}
})
return res
}
return null
}
服务器:
[HttpPost("uploadproductimage")]
public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
{
return Ok();
}
错误,因为服务器期望参数“image”而不是“img”:
formData.append("img", event);
public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
分享我使用React和HTML输入的经验
定义输入字段
<input type="file" onChange={onChange} accept ="image/*"/>
定义onChange监听器
const onChange = (e) => {
let url = "https://<server-url>/api/upload";
let file = e.target.files[0];
uploadFile(url, file);
};
const uploadFile = (url, file) => {
let formData = new FormData();
formData.append("file", file);
axios.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
}).then((response) => {
fnSuccess(response);
}).catch((error) => {
fnFail(error);
});
};
const fnSuccess = (response) => {
//Add success handling
};
const fnFail = (error) => {
//Add failed handling
};