Javascript FormData仅发布一个图像文件
我想将多个图像文件发布到服务器。我使用了formData(formDta.append()),它只获取一个图像。。它没有拍摄多张照片Javascript FormData仅发布一个图像文件,javascript,reactjs,form-data,Javascript,Reactjs,Form Data,我想将多个图像文件发布到服务器。我使用了formData(formDta.append()),它只获取一个图像。。它没有拍摄多张照片 **#contained-button-file** is the input file ID uploadCategoryImages = () => { let formData = new FormData() let imagefile = document.querySelector('#contained-button-fil
**#contained-button-file** is the input file ID
uploadCategoryImages = () => {
let formData = new FormData()
let imagefile = document.querySelector('#contained-button-file')
formData.append('image', imagefile.files[0])
api.post('/api/v1/addimage/category/3', formData)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
alert(error)
})
}
当前实现仅尝试附加
imagefile.files
的第一个元素(0
)
可以用来附加每个元素
还需要一个名称作为它的第一个参数,后跟一个值,最后是一个可选的文件名
有关实际示例,请参见下文
[...imagefile.files].forEach(file => formData.append('image[]', file))
总的来说,您的uploadCategoryImages
功能可以简化为以下内容:
uploadCategoryImages = () => {
const data = new FormData()
const images = document.getElementById('contained-button-file').files
[...images].forEach(image => data.append('image[]', image))
api.post('/api/v1/addimage/category/3', data)
.then(console.log)
.catch(alert)
}
是
FormData
字段可以一次分配一个文件,但您可以在FormData
中追加多个文件,如下所示
uploadCategoryImages = () => {
let formData = new FormData();
let imagefile = document.querySelector('#contained-button-file');
//loop through file elements and append file in formdata
for(var i = 0; i <imagefile.files.length; i++){
//you can name it anything here it will be image-0, image-1 like so
formData.append('image-'+ i, imagefile.files[i]);
}
api.post('/api/azz/a/ss/ss/ss/s/', formData)
.then(function (response)
{
console.log(response)
alert("Images have been uploaded Succesfully!!!");
})
.catch(function (error) {
alert(error)
})
}
uploadCategoryImages=()=>{
设formData=new formData();
让imagefile=document.querySelector(“#包含的按钮文件”);
//循环文件元素并在formdata中追加文件
对于(var i=0;i我得到“imagefile.files.forEach不是函数”这一错误我的错误。文件
是一个(不是数组),因此需要强制转换(使用或@RamyaMiiM^(为了使用)-否则一个or语句就足够了。无法在FormData中附加多个图像我已将答案中的name参数修改为'image[]'
。中的第三个片段建议它应该在@RamyaMiiM下工作