2024-07-11 21:25:58 +08:00
|
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
"net/http"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2024-07-12 20:32:33 +08:00
|
|
|
|
"picgo/configs"
|
2024-07-11 21:25:58 +08:00
|
|
|
|
"picgo/corelib"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func UploadFileHandler(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
if r.Method == "POST" {
|
2024-07-12 20:32:33 +08:00
|
|
|
|
// 解析表单数据,限制最大内存为3MB 1024*1024*3
|
|
|
|
|
err := r.ParseMultipartForm(configs.Settings.Server.UploadMaxSize << 20)
|
2024-07-11 21:25:58 +08:00
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
|
// 保存文件到本地
|
2024-07-12 20:32:33 +08:00
|
|
|
|
f, err := os.OpenFile(filepath.Join(configs.Settings.Server.UploadPath, handler.Filename), os.O_WRONLY|os.O_CREATE, 0666)
|
2024-07-11 21:25:58 +08:00
|
|
|
|
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)
|
2024-07-12 20:32:33 +08:00
|
|
|
|
corelib.WriteJsonResponse(w, 200, "文件上传成功", nil)
|
|
|
|
|
//corelib.Success(w)
|
2024-07-11 21:25:58 +08:00
|
|
|
|
} else {
|
|
|
|
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
|
|
|
|
}
|
|
|
|
|
}
|