package controllers import ( "eta/eta_mobile/models" "eta/eta_mobile/services" "eta/eta_mobile/utils" "os" "path" "time" ) // banner type BannerController struct { BaseAuthController } // @Title 图片上传 // @Description 图片上传接口 // @Param File query file true "文件" // @Success 200 新增成功 // @router /upload [post] func (this *BannerController) Upload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() f, h, err := this.GetFile("file") if err != nil { br.Msg = "获取资源信息失败" br.ErrMsg = "获取资源信息失败,Err:" + err.Error() return } ext := path.Ext(h.Filename) dateDir := time.Now().Format("20060102") uploadDir := utils.STATIC_DIR + "hongze/" + dateDir err = os.MkdirAll(uploadDir, utils.DIR_MOD) if err != nil { br.Msg = "存储目录创建失败" br.ErrMsg = "存储目录创建失败,Err:" + err.Error() return } randStr := utils.GetRandStringNoSpecialChar(28) fileName := randStr + ext fpath := uploadDir + "/" + fileName defer f.Close() //关闭上传文件 err = this.SaveToFile("file", fpath) if err != nil { br.Msg = "文件上传失败" br.ErrMsg = "文件上传失败,Err:" + err.Error() return } resourceUrl := `` //resourceUrl, err = services.UploadImgToMinIoTest(fileName, fpath) //if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return //} ossClient := services.NewOssClient() if ossClient == nil { br.Msg = "上传失败" br.ErrMsg = "初始化OSS服务失败" return } resourceUrl, err = ossClient.UploadFile(fileName, fpath, "") if err != nil { br.Msg = "文件上传失败" br.ErrMsg = "文件上传失败,Err:" + err.Error() return } ////上传到阿里云 和 minio //if utils.ObjectStorageClient == "minio" { // resourceUrl, err = services.UploadImgToMinIo(fileName, fpath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } //} else { // resourceUrl, err = services.UploadAliyunV2(fileName, fpath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } //} defer func() { os.Remove(fpath) }() item := new(models.Resource) item.ResourceUrl = resourceUrl item.ResourceType = 1 item.CreateTime = time.Now() newId, err := models.AddResource(item) if err != nil { br.Msg = "资源上传失败" br.ErrMsg = "资源上传失败,Err:" + err.Error() return } resp := new(models.ResourceResp) resp.Id = newId resp.ResourceUrl = resourceUrl br.Msg = "上传成功" br.Ret = 200 br.Success = true br.Data = resp return }