package main import ( "io" "net/http" "os" "path/filepath" "strings" "hnyfkj.com.cn/rtu/linux/baseapp" ) const maxUploadSize = 1 << 30 // 1GB func uploadUserAPP(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize) err := r.ParseMultipartForm(maxUploadSize) if err != nil { http.Error(w, "解析上传文件失败: "+err.Error(), http.StatusBadRequest) return } file, header, err := r.FormFile("file") if err != nil { http.Error(w, "获取上传文件失败: "+err.Error(), http.StatusBadRequest) return } defer file.Close() if !strings.HasSuffix(strings.ToLower(header.Filename), ".tar.gz") { http.Error(w, "只允许上传 tar.gz 类型的文件", http.StatusBadRequest) return } path := filepath.Join("/tmp", filepath.Base(header.Filename)) err = saveUploadFile(file, path) if err != nil { http.Error(w, "保存上传文件失败: "+err.Error(), http.StatusInternalServerError) return } baseapp.Logger.Infof( "[上传文件成功] 上传文件名: %s, 上传文件大小: %d 字节, 本地存储路径: %s", header.Filename, header.Size, path) w.WriteHeader(http.StatusOK) } func saveUploadFile(src io.Reader, path string) error { dst, err := os.Create(path) if err != nil { return err } defer dst.Close() _, err = io.Copy(dst, src) if err != nil { os.Remove(path) return err } return nil }