package services import ( "errors" "hongze/hz_crm_api/models" "hongze/hz_crm_api/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, 766) 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 = UploadAliyunV2(newFileName, fpath) if err != nil { err = errors.New("文件上传失败,Err:" + err.Error()) return } defer func() { os.Remove(fpath) }() item := new(models.Resource) item.ResourceUrl = resourceUrl item.ResourceType = 1 item.CreateTime = time.Now() _, err = models.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 }