我读了this博客和 this问题及其答案,但发现他们只谈论单个文件
// Parse our multipart form, 10 << 20 specifies a maximum
// upload of 10 MB files.
r.ParseMultipartForm(10 << 20)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, handler, err := r.FormFile("myFile")
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer file.Close()
如何一次上传多个文件?如果我有以下上传多个文件的 JavaScript 代码,我如何在 Go 服务器中读取处理它
const formData = new FormData();
const photos = document.querySelector('input[type="file"][multiple]');
formData.append('title', 'My Vegas Vacation');
for (let i = 0; i < photos.files.length; i++) {
formData.append('photos', photos.files[i]);
}
fetch('https://example.com/posts', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
使用 HTML 元素:<input type="file" multiple />
或与:const formData = new FormData();
/*more specific selector:
"input[type=file][name=file1],input[type=file][name=file2],input[type=file][name=file3]"*/
document.querySelectorAll("input[type=file]").forEach(
input=>formData.append('photos',input.files[0]);
如果 HTML 元素是分开的,例如:<input name="file1" type="file" />
<input name="file2" type="file" />
<input name="file3" type="file" />
最佳答案
Request.FormFile是访问 Request.MultipartForm 中单个文件的辅助方法.使用Request.MultipartForm直接访问多个文件的 key :
err := r.ParseMultipartForm(10 << 20)
if err != nil {
// handle error
}
for _, fh := range r.MultipartForm.File["photos"] {
f, err := fh.Open()
if err != nil {
// Handle error
}
// Read data from f
f.Close()
}
如果输入元素具有与最后一个 HTML 片段一样的唯一键,则调用 r.FormFile(key)
对于每个唯一键。
关于go - 是否可以一次上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63319613/