1 回答

TA貢獻(xiàn)1846條經(jīng)驗 獲得超7個贊
很難猜測你的代碼在哪里恐慌。原因可能是您的程序在發(fā)生錯誤時繼續(xù)執(zhí)行。例如,如果創(chuàng)建文件失敗,將死機(jī),因為 為零。outfile.Close()outfile
這兩種方法都支持單個字段的多個文件。不同之處在于它們?nèi)绾翁幚韮?nèi)存。流式處理版本從網(wǎng)絡(luò)讀取一小部分?jǐn)?shù)據(jù),并在您調(diào)用 時將其寫入文件。另一個變體在您調(diào)用 時將所有數(shù)據(jù)加載到內(nèi)存中,因此它需要與要傳輸?shù)奈募笮∫粯佣嗟膬?nèi)存。您將在下面找到兩種變體的工作示例。io.CopyParseMultiForm()
流媒體變體:
func storeFile(part *multipart.Part) error {
name := part.FileName()
outfile, err := os.Create("uploads/" + name)
if err != nil {
return err
}
defer outfile.Close()
_, err = io.Copy(outfile, part)
if err != nil {
return err
}
return nil
}
func filePOST(w http.ResponseWriter, r *http.Request) error {
fmt.Println("File Upload Endpoint Hit")
mr, err := r.MultipartReader()
if err != nil {
return err
}
for {
part, err := mr.NextPart()
// This is OK, no more parts
switch {
case errors.Is(err, io.EOF):
fmt.Println("done")
return nil
case err != nil:
// Some error
return err
default:
switch part.FormName() {
case "coverArt", "profile", "songs", "videos":
if err := storeFile(part); err != nil {
return err
}
}
}
}
}
func main() {
http.HandleFunc("/upload", func(writer http.ResponseWriter, request *http.Request) {
err := filePOST(writer, request)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
log.Println("Error", err)
}
})
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
版本帶有 ,它將數(shù)據(jù)讀取到內(nèi)存。ParseMultipartForm
func storeFile(part *multipart.FileHeader) error {
name := part.Filename
infile, err := part.Open()
if err != nil {
return err
}
defer infile.Close()
outfile, err := os.Create("uploads/" + name)
if err != nil {
return err
}
defer outfile.Close()
_, err = io.Copy(outfile, infile)
if err != nil {
return err
}
return nil
}
func FilePOST(w http.ResponseWriter, r *http.Request) error {
fmt.Println("File Upload Endpoint Hit")
if err := r.ParseMultipartForm(2 << 24); err != nil {
return err
}
for _, fileType := range []string{"coverArt", "profile", "songs", "videos"} {
uploadedFiles, exists := r.MultipartForm.File[fileType]
if !exists {
continue
}
for _, file := range uploadedFiles {
if err := storeFile(file); err != nil {
return err
}
}
}
return nil
}
func main() {
http.HandleFunc("/upload", func(writer http.ResponseWriter, request *http.Request) {
err := FilePOST(writer, request)
if err != nil {
http.Error(writer, err.Error(), http.StatusInternalServerError)
log.Println("Error", err)
}
})
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
- 1 回答
- 0 關(guān)注
- 94 瀏覽
添加回答
舉報