Beego 似乎没有上传多个文件的便捷方法。GetFile() 只是从标准库中包装 FromFile()。您可能想要使用标准库的阅读器函数:r.MultipartReader()。
在这种情况下,我通常通过调用从控制器公开响应读取器和写入器:
w = this.Ctx.ResponseWriter
r = this.Ctx.ResponseReader
现在我能够以标准方式使用 net/http 包并在框架外部实施解决方案。
快速搜索在 Go 中上传多个文件会引导我找到有用的博客文章。
为了保护这个答案免受链接腐烂,这是作者的解决方案:
func uploadHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
//GET displays the upload form.
case "GET":
display(w, "upload", nil)
//POST takes the uploaded file(s) and saves it to disk.
case "POST":
//get the multipart reader for the request.
reader, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//copy each part to destination.
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
//if part.FileName() is empty, skip this iteration.
if part.FileName() == "" {
continue
}
dst, err := os.Create("/home/sanat/" + part.FileName())
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := io.Copy(dst, part); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
//display success message.
display(w, "upload", "Upload successful.")
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}