它似乎没有像Beego有一个方便的方法来上传多个文件。 GetFile()仅包含标准库中的FromFile()。您可能想要使用标准库的阅读器功能:r.MultipartReader()。
在这样的情况下,我一般是通过调用暴露从控制器的响应读写器:
w = this.Ctx.ResponseWriter
r = this.Ctx.ResponseReader
现在我可以使用net/HTTP包中的标准方法和实施方案外到框架。
在Go上快速搜索上传多个文件会将我引导至blog post。
在保护这个答案从链接腐烂的利益,这里是作者的解决方案:
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)
}
}
如何添加图片,就像我们在网站上看到的一样。显示添加图像的图标。 – 2015-06-09 06:50:41
使用r = this.Ctx.Request代替r = this.Ctx.ResponseReader – 2016-04-19 14:16:30