我知道如何上传单个文件,但现在我正在尝试在同一个golang函数中上传多个文件。
这是我的代码:
func PhotoCreatePOST(w http.ResponseWriter,r * http.Request){ var …
好的,谢谢 这个 伟大的博客文章,我找到了我的答案,在这里它是记录的完整解决方案:
// PhotoCreatePOST saves multiple photo uploads func PhotoCreatePOST(w http.ResponseWriter, r *http.Request) { err := r.ParseMultipartForm(100000) if err != nil { fmt.Println("error parsing multiplepart form", err) return } files := r.MultipartForm.File["files"] for i, _ := range files { //Iterate over multiple uploaded files file, err := files[i].Open() defer file.Close() if err != nil { fmt.Println("error opening file ", err) return } ext := path.Ext(files[i].Filename) //TODO: Verify extension is valid filename := GetRandomString(10) + ext //create destination file making sure the path is writeable. dst, err := os.Create("media/photos/" + filename) defer dst.Close() if err != nil { fmt.Println("error creating destination ", err) return } //copy the uploaded file to the destination file if _, err := io.Copy(dst, file); err != nil { fmt.Println("error copying file", err) return } fmt.Println("Image upload success: ", files[i].Filename) } fmt.Println("all are uploaded") PhotoCreateGET(w, r) return } //Generate random filename (never trust user input!) var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789") // GetString returns a random string func GetRandomString(n int) string { rand.Seed(time.Now().UnixNano()) b := make([]rune, n) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] } return string(b) }
上传表格:
<form method="post" action="/create/photo" enctype="multipart/form-data"> <input type="file" name="files" multiple> <input type="hidden" name="token" value="{{.token}}"> <button title="submit" type="submit" >Save </button> </form>
瞧。希望它可以为其他人节省一些时间。