picgo/handler/upload.go

54 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"picgo/corelib"
)
func UploadFileHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// 解析表单数据限制最大内存为32MB
err := r.ParseMultipartForm(32 << 20)
if err != nil {
corelib.WriteJsonResponse(w, 1020, "文件大于32MB", nil)
return
}
// 获取文件句柄
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println("Error retrieving the file")
fmt.Println(err)
corelib.WriteJsonResponse(w, 1021, "获取文件失败", nil)
return
}
defer file.Close()
// 保存文件到本地
f, err := os.OpenFile(filepath.Join("./static/pic", handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("Error saving file")
fmt.Println(err)
corelib.WriteJsonResponse(w, 1023, "创建文件失败", nil)
return
}
defer f.Close()
// 将文件内容拷贝到本地文件
_, err = io.Copy(f, file)
if err != nil {
fmt.Println("Error copying file")
fmt.Println(err)
corelib.WriteJsonResponse(w, 1024, "保存文件失败", nil)
return
}
//fmt.Fprintf(w, "File %s uploaded successfully!", handler.Filename)
corelib.Success(w)
} else {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}