package handler import ( "fmt" "io" "net/http" "os" "path/filepath" "picgo/configs" "picgo/corelib" ) func UploadFileApiHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { // 解析表单数据,限制最大内存为3MB 1024*1024*3 err := r.ParseMultipartForm(configs.Settings.Server.UploadMaxSize << 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(configs.Settings.Server.UploadPath, 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.WriteJsonResponse(w, 200, "文件上传成功", nil) //corelib.Success(w) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } }