54 lines
1.3 KiB
Go
54 lines
1.3 KiB
Go
|
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)
|
|||
|
}
|
|||
|
}
|