我正在使用reactjs创建相册。我正在使用loopback-storage-connector
存储图像。
这是我上传图片的代码
fileUploadCarImg =()=>{
for (let index = 0; index < this.state.file.length; index++) {
const element = this.state.file[index];
const fd = new FormData();
fd.append('image2',element,element.name )
axios.post('http://localhost:3000/api/attachmentBanks/Car_Image/upload',fd , {
onUploadProgress : ProgressEvent => {
console.log('Upload Progress: ' + Math.round(ProgressEvent.loaded / ProgressEvent.total *100) + '%')
}
})
.then(res => {
console.log(res.data.result.files.image2[0].name)
});
}
}
我想将这些图像名称存储到loopback-mysql-connector
中。所以我的想法是将每个图像名称(res.data.result.files.image2[0].name
)存储到一个数组中。
上传图片console.log(this.state.file)
打印时
Array(8) [ File, File, File, File, File, File, File, File ]
(8) […]
0: File { name: "IMG_20150905_072534.jpg", lastModified: 1442772056000, size: 241381, … }
1: File { name: "IMG_20151110_115108.jpg", lastModified: 1447206282000, size: 2749010, … }
2: File { name: "IMG_20151110_115124.jpg", lastModified: 1447206242000, size: 2797533, … }
3: File { name: "IMG_20151110_120625.jpg", lastModified: 1447205916000, size: 725661, … }
4: File { name: "IMG_20151110_120642.jpg", lastModified: 1447206122000, size: 687308, … }
5: File { name: "IMG_20151110_120704.jpg", lastModified: 1447205958000, size: 3364141, … }
6: File { name: "IMG_20151110_121043.jpg", lastModified: 1447205998000, size: 2921138, … }
7: File { name: "IMG_20151110_121050.jpg", lastModified: 1447206044000, size: 3867974, … }
length: 8
<prototype>: [
我只需要存储图像的名称。 有人给我解决问题的提示吗?
答案 0 :(得分:1)
我建议使用Array.prototype.map()函数:
const names = res.data.result.files.map((file) => file.image2[0].name);
很难解码数组,但稍作调整便可以工作。
答案 1 :(得分:1)
请考虑使用await
let data = [];
for (let index = 0; index < this.state.file.length; index++) {
const element = this.state.file[index];
const fd = new FormData();
fd.append('image2',element,element.name )
try {
const res = await axios.post('http://localhost:3000/api/attachmentBanks/Car_Image/upload',fd , {
onUploadProgress : ProgressEvent => {
console.log('Upload Progress: ' + Math.round(ProgressEvent.loaded / ProgressEvent.total *100) + '%')
}
});
data.push(res.data.result.files.image2[0].name);
} catch(error) {
//your handler
}
}