如何使用Axios将图像发送到节点js? [英] How do you send images to node js with Axios?
问题描述
有没有办法使用axios将一组图像(或单个图像)发送到节点?
Is there a way to send an array of images (or a single image) to node using axios?
我正在使用的axios代码(我是在前端使用react js):
the axios code I'm using(I'm using react js on the front end):
onFormSubmit(event){
event.preventDefault();
let payload = this.state;
console.log("in onFormSubmit!!! with state: ", this.state, "and payload: ", payload);
axios.post('/api/art', payload)
.then(function(response){
console.log('saved successfully')
});
我所做的研究表明,可能没有受到支持的方式使用axios将图像文件发送到节点,但这对我来说似乎很奇怪。有办法吗?
The research I've done suggests that perhaps there isn't a supported way to send image files to node using axios, but this seems strange to me. Is there a way?
推荐答案
以下是我正常工作的方法。我不得不使用一个名为FormData的对象。我使用了导入:
Here is the way I got this to work properly. I had to make use of an object called FormData. I used the import:
import FormData from 'form-data'
当然在这次导入之前我必须为它运行npm install:
Of course before this import I had to run the npm install for it:
npm install --save form-data
一旦我完成了所有这些,这里是我如何在我的行动中使用它:
Once I did all that, here is how I used it within my action:
let data = new FormData();
data.append('file', file, file.fileName);
return (dispatch) => {
axios.post(URL, data, {
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
}
})
.then((response) => {
//handle success
}).catch((error) => {
//handle error
});
};}
这里需要注意的重要事项是:
The important pieces to note here are:
- 在数据对象传递到axios.post调用之后,我将一些头文件作为配置对象包含在内。您在此处包含的内容类型是关键。您正在提交多部分/表单数据内容类型。
- 在该Content类型标题中,我还添加了一个边界,该边界派生自您之前创建的数据对象。
- 这里使用的'文件'只是我传递给我的动作的文件对象。它只是我用于对象的名称,你可以在这里使用你想要的任何东西。
希望这会有所帮助,这可以解决我尝试向后端提交图像时遇到的所有问题(在我的情况下是休息服务 - 通过电话会议)。
Hope this helps, this cleared up all of the issues I had with trying to submit an image to a backend (in my case a rest service - through a post call).
这篇关于如何使用Axios将图像发送到节点js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!