最近項目中用到beego,需要實現文件批量上傳,翻了好久beego的文檔都沒有找到滿意的解決辦法,結果看源碼時發現作者已經給出了相關實現代碼,在源碼包controller.go文件中560-586行,記錄如下:
//GetFiles return multi-upload files
files, err:=c.GetFiles("myfiles")
if err != nil {
http.Error(w, err.Error(), http.StatusNoContent)
return
}
for i, _ := range files {
//for each fileheader, get a handle to the actual file
file, err := files[i].Open()
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//create destination file making sure the path is writeable.
dst, err := os.Create("upload/" + files[i].Filename)
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//copy the uploaded file to the destination file
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
對應的input標簽需設置
multiple
屬性
<input type="file" multiple name="myfiles">