file.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package services
  2. import (
  3. "errors"
  4. "hongze/hz_eta_api/models"
  5. "hongze/hz_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, 766)
  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. //上传到阿里云
  28. resourceUrl, err = UploadAliyunV2(newFileName, fpath)
  29. if err != nil {
  30. err = errors.New("文件上传失败,Err:" + err.Error())
  31. return
  32. }
  33. defer func() {
  34. os.Remove(fpath)
  35. }()
  36. item := new(models.Resource)
  37. item.ResourceUrl = resourceUrl
  38. item.ResourceType = 1
  39. item.CreateTime = time.Now()
  40. _, err = models.AddResource(item)
  41. if err != nil {
  42. err = errors.New("资源上传失败,Err:" + err.Error())
  43. return
  44. }
  45. return
  46. }
  47. // saveToFile 保存到本地文件
  48. func saveToFile(fileMulti multipart.File, tofile string) error {
  49. f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  50. if err != nil {
  51. return err
  52. }
  53. defer f.Close()
  54. io.Copy(f, fileMulti)
  55. return nil
  56. }