upload.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package controller
  2. import (
  3. "cold-logistics/common/file_store"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "github.com/google/uuid"
  7. "gogs.baozhida.cn/zoie/OAuth-core/api"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. )
  13. type UploadController struct {
  14. api.Api
  15. }
  16. // FilesUpload 文件上传
  17. // @Summary 文件上传
  18. // @Description 文件上传
  19. // @Tags 工具
  20. // @Success 200 {object} response.Response{data=string,id=string,msg=string} "{"code": 200, "data": [...]}"
  21. // @Router /api/captcha [get]
  22. func (e UploadController) FilesUpload(c *gin.Context) {
  23. err := e.MakeContext(c).Errors
  24. if err != nil {
  25. e.Error(500, err, "服务初始化失败!")
  26. return
  27. }
  28. // 处理文件上传逻辑
  29. file, err := c.FormFile("file")
  30. //bizType := c.PostForm("bizType")
  31. //correlationCode := c.PostForm("correlationCode")
  32. uploadFileName := file.Filename // 获取文件名
  33. fileType := filepath.Ext(uploadFileName) // 获取文件类型(扩展名)
  34. if err != nil {
  35. c.JSON(400, gin.H{"error": err.Error()})
  36. return
  37. }
  38. filePath := file_store.GetCurrentDirectory() + "/uploads/" + uploadFileName
  39. err = c.SaveUploadedFile(file, filePath)
  40. if err != nil {
  41. c.JSON(400, gin.H{"error": err.Error()})
  42. return
  43. }
  44. defer func() {
  45. os.Remove(filePath)
  46. }()
  47. // TODO: 文件上传到省平台
  48. filename := fmt.Sprintf("%s/%s%s", time.Now().Format("2006-01-02"), strings.Replace(uuid.New().String(), "-", "", -1), fileType)
  49. err = file_store.QiniuFileStore.UpLoad(filename, filePath)
  50. if err != nil {
  51. c.JSON(400, gin.H{"error": "文件上传失败"})
  52. return
  53. }
  54. e.Custom(gin.H{
  55. "code": 200,
  56. "data": filename,
  57. "msg": "success",
  58. })
  59. }