upload.go 1.5 KB

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