1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package services
- import (
- "errors"
- "hongze/hongze_mobile_admin/models/tables/resource"
- "hongze/hongze_mobile_admin/utils"
- "io"
- "mime/multipart"
- "os"
- "time"
- )
- // UploadToOssAndFileName 上传到oss并使用这个名称
- func UploadToOssAndFileName(fileMulti multipart.File, newFileName string) (resourceUrl string, err error) {
- dateDir := time.Now().Format("20060102")
- uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
- err = os.MkdirAll(uploadDir, 0766)
- if err != nil {
- err = errors.New("存储目录创建失败,Err:" + err.Error())
- return
- }
- //本地地址
- fpath := uploadDir + "/" + newFileName
- err = saveToFile(fileMulti, fpath)
- if err != nil {
- err = errors.New("文件上传失败,Err:" + err.Error())
- return
- }
- //上传到阿里云
- resourceUrl, err = UploadAliyun(newFileName, fpath)
- if err != nil {
- err = errors.New("文件上传失败,Err:" + err.Error())
- return
- }
- defer func() {
- os.Remove(fpath)
- }()
- item := new(resource.Resource)
- item.ResourceUrl = resourceUrl
- item.ResourceType = 1
- item.CreateTime = time.Now()
- _, err = resource.AddResource(item)
- if err != nil {
- err = errors.New("资源上传失败,Err:" + err.Error())
- return
- }
- return
- }
- // saveToFile 保存到本地文件
- func saveToFile(fileMulti multipart.File, tofile string) error {
- f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
- if err != nil {
- return err
- }
- defer f.Close()
- io.Copy(f, fileMulti)
- return nil
- }
|