Upload @Summary Upload a file @Description Upload a file @Tags Upload @Accept mpfd @Produce json @Param file formData file true "file" @Param upload_target formData string false "上传目标,attachment=附件上传,my_uploads=同步到我的上传" @Security BearerAuth @Success 20
(c *gin.Context)
| 30 | // @Success 200 {object} model.CommonResponse{data=model.UploadFile} "success" |
| 31 | // @Router /api/upload [post] |
| 32 | func Upload(c *gin.Context) { |
| 33 | // upload file |
| 34 | fileHeader, err := c.FormFile("file") |
| 35 | if err != nil { |
| 36 | c.JSON(http.StatusBadRequest, model.ParamError.ToResponse(err)) |
| 37 | return |
| 38 | } |
| 39 | if fileHeader.Size > config.MAX_UPLOAD_FILE_SIZE { |
| 40 | c.JSON(http.StatusBadRequest, model.FileError.ToResponse(errors.New("The maximum allowed size for file uploads is "+config.MAX_UPLOAD_FILE_SIZE_STRING+"."))) |
| 41 | return |
| 42 | } |
| 43 | |
| 44 | uploadTarget := strings.ToLower(strings.TrimSpace(c.PostForm("upload_target"))) |
| 45 | if uploadTarget == "" { |
| 46 | uploadTarget = "attachment" |
| 47 | } |
| 48 | |
| 49 | eid := config.GetEID(c) |
| 50 | user_id := config.GetUserId(c) |
| 51 | if eid == 0 || user_id == 0 { |
| 52 | c.JSON(http.StatusBadRequest, model.AuthFailed.ToResponse(nil)) |
| 53 | return |
| 54 | } |
| 55 | file, err := fileHeader.Open() |
| 56 | if err != nil { |
| 57 | c.JSON(http.StatusBadRequest, model.FileError.ToResponse(err)) |
| 58 | return |
| 59 | } |
| 60 | defer file.Close() |
| 61 | |
| 62 | // 先读取文件内容 |
| 63 | fileContent, err := io.ReadAll(file) |
| 64 | if err != nil && err != io.EOF { |
| 65 | c.JSON(http.StatusBadRequest, model.FileError.ToResponse(err)) |
| 66 | return |
| 67 | } |
| 68 | |
| 69 | // 计算哈希前重置文件指针 |
| 70 | if _, err := file.Seek(0, 0); err != nil { |
| 71 | c.JSON(http.StatusBadRequest, model.FileError.ToResponse(err)) |
| 72 | return |
| 73 | } |
| 74 | hashStr, err := storage.GetFileHash(file) |
| 75 | if err != nil { |
| 76 | c.JSON(http.StatusBadRequest, model.FileError.ToResponse(err)) |
| 77 | return |
| 78 | } |
| 79 | |
| 80 | extension := path.Ext(fileHeader.Filename) |
| 81 | PreviewKey, err := model.GetPreviewKey(hashStr, extension, eid) |
| 82 | if err != nil { |
| 83 | c.JSON(http.StatusBadRequest, model.FileError.ToResponse(err)) |
| 84 | return |
| 85 | } |
| 86 | |
| 87 | key := model.GetFileKey(PreviewKey, eid, user_id) |
| 88 | err = storage.StorageInstance.Save(fileContent, key) |
| 89 | if err != nil { |
nothing calls this directly
no test coverage detected