// @Author gmy 2024/9/24 17:56:00 package controllers import ( "eta/eta_hub/models" "eta/eta_hub/services" "eta/eta_hub/utils" "os" "path" "time" ) type ResourceDealWithController struct { BaseAuthController } // FileUpload // @Title 文件上传 // @Description 文件上传接口 // @Param File query file true "文件" // @Param AiChatTopicId query int true "主题id" // @Success 200 {object} models.ResourceResp // @router /file/upload [post] func (this *ResourceDealWithController) FileUpload() { 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 } /*fileData, e := ioutil.ReadAll(f) if e != nil { br.Msg = "上传失败" br.ErrMsg = "读取文件失败, Err: " + e.Error() return } pass := filetype.IsImage(fileData) if !pass { br.Msg = "文件格式有误" br.ErrMsg = "文件格式有误" return }*/ uploadFileName := h.Filename //上传的文件名 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 := `` 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 } 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 := models.ResourceResp{ Id: newId, ResourceUrl: resourceUrl, ResourceName: uploadFileName, } br.Msg = "上传成功" br.Ret = 200 br.Data = resp return }