file.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package services
  2. import (
  3. "errors"
  4. "eta/eta_api/models"
  5. "eta/eta_api/utils"
  6. "io"
  7. "mime/multipart"
  8. "os"
  9. "time"
  10. )
  11. // UploadToOssAndFileName 上传到oss并使用这个名称
  12. func UploadToOssAndFileName(fileMulti multipart.File, newFileName string) (resourceUrl string, err error) {
  13. dateDir := time.Now().Format("20060102")
  14. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  15. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  16. if err != nil {
  17. err = errors.New("存储目录创建失败,Err:" + err.Error())
  18. return
  19. }
  20. //本地地址
  21. fpath := uploadDir + "/" + newFileName
  22. err = saveToFile(fileMulti, fpath)
  23. if err != nil {
  24. err = errors.New("文件上传失败,Err:" + err.Error())
  25. return
  26. }
  27. //上传到阿里云 和 minio
  28. if utils.ObjectStorageClient == "minio" {
  29. resourceUrl, err = UploadImgToMinIo(newFileName, fpath)
  30. if err != nil {
  31. err = errors.New("文件上传失败,Err:" + err.Error())
  32. return
  33. }
  34. } else {
  35. resourceUrl, err = UploadAliyunV2(newFileName, fpath)
  36. if err != nil {
  37. err = errors.New("文件上传失败,Err:" + err.Error())
  38. return
  39. }
  40. }
  41. defer func() {
  42. os.Remove(fpath)
  43. }()
  44. item := new(models.Resource)
  45. item.ResourceUrl = resourceUrl
  46. item.ResourceType = 1
  47. item.CreateTime = time.Now()
  48. _, err = models.AddResource(item)
  49. if err != nil {
  50. err = errors.New("资源上传失败,Err:" + err.Error())
  51. return
  52. }
  53. return
  54. }
  55. // saveToFile 保存到本地文件
  56. func saveToFile(fileMulti multipart.File, tofile string) error {
  57. f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  58. if err != nil {
  59. return err
  60. }
  61. defer f.Close()
  62. io.Copy(f, fileMulti)
  63. return nil
  64. }