package controllers import ( "bufio" "encoding/base64" "eta_gn/eta_api/models" "eta_gn/eta_api/services" "eta_gn/eta_api/utils" "fmt" "github.com/h2non/filetype" "github.com/kgiannakakis/mp3duration/src/mp3duration" "io" "io/ioutil" "net/http" "os" "path" "regexp" "strconv" "strings" "time" rdHttp "github.com/rdlucklib/rdluck_tools/http" ) // 资源管理-图片上传,合同上传等 type ResourceController struct { //BaseAuthController BaseCommonController } // ResourceAuthController 文件资源 type ResourceAuthController struct { BaseAuthController } // @Title 图片上传 // @Description 图片上传接口 // @Param file query file true "文件" // @Success 200 {object} models.ResourceResp // @router /image/upload [post] func (this *ResourceController) 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 } 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 := `` //上传到阿里云 和 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 // } //} 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.Success = true br.Data = resp return } // @Title 视频上传 // @Description 视频上传接口 // @Param file query file true "文件" // @Success 200 新增成功 // @router /video/upload [post] func (this *ResourceController) VideoUpload() { utils.FileLog.Info("start VideoUpload ") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) 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.IsVideo(fileData) if !pass { br.Msg = "文件格式有误" br.ErrMsg = "文件格式有误" return } ext := path.Ext(h.Filename) dateDir := time.Now().Format("20060102") uploadDir := utils.STATIC_DIR + "hongze/" + dateDir //uploadDir := "./" + dateDir fmt.Println(uploadDir) 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() //关闭上传文件 utils.FileLog.Info("start save") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) utils.FileLog.Info("fpath %s:", fpath) fileHandle, err := os.OpenFile(fpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModeAppend) if err != nil { br.Msg = "创建文件失败" br.ErrMsg = "创建文件失败,Err:" + err.Error() return } defer fileHandle.Close() //循环读取 for { buffer := make([]byte, 4096) _, err := f.Read(buffer) //如果错误信息是其他类型的,则直接panic if err != nil && err != io.EOF { br.Msg = "上传失败" br.ErrMsg = "读取文件内容失败,Err:" + err.Error() return } //注意,错误信息是以io包的EOF时,表示读取到文件末尾 if err == io.EOF { break } // NewWriter 默认缓冲区大小是 4096 // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法 buf := bufio.NewWriter(fileHandle) // 字节写入 // 字符串写入 buf.WriteString(string(buffer)) // 将缓冲中的数据写入 err = buf.Flush() if err != nil { br.Msg = "上传失败" br.ErrMsg = "写入文件内容失败,Err:" + err.Error() return } } utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) utils.FileLog.Info("end save") //err = this.SaveToFile("file", fpath) //if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return //} /* fmt.Println("start") fmt.Println(time.Now()) tofile:="./20201123.mp4" fromFile:="./第五期下.mp4" f, err := os.Open(fromFile) defer f.Close() //注意要关闭文件 fileHandle, err := os.OpenFile(tofile, os.O_RDONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { fmt.Println("open file error :", err) return } defer fileHandle.Close() if err != nil { panic(err) } else { //循环读取 for { buffer := make([]byte, 4096) _, err := f.Read(buffer) //如果错误信息是其他类型的,则直接panic if err != nil && err != io.EOF { panic(err) } //注意,错误信息是以io包的EOF时,表示读取到文件末尾 if err == io.EOF { fmt.Println("读取完毕") break } // NewWriter 默认缓冲区大小是 4096 // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法 buf := bufio.NewWriter(fileHandle) // 字节写入 // 字符串写入 buf.WriteString(string(buffer)) // 将缓冲中的数据写入 err = buf.Flush() if err != nil { fmt.Println("flush error :"+err.Error()) return } } } */ utils.FileLog.Info("start update oss ") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) //savePath := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/") //savePath += fileName defer func() { _ = os.Remove(fpath) }() //上传到阿里云 和 minio resourceUrl := `` //if utils.ObjectStorageClient == "minio" { // err = services.UploadVideoToMinIo(fileName, fpath, savePath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } // resourceUrl = utils.MinIoImghost + savePath //} else { // err = services.UploadVideoAliyun(fileName, fpath, savePath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } // resourceUrl = utils.Imghost + savePath //} 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 } utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) utils.FileLog.Info("end update oss ") item := new(models.Resource) item.ResourceUrl = resourceUrl item.ResourceType = 3 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 utils.FileLog.Info("start GetMP4Duration ") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) duration, err := services.GetMP4Duration(f) if err != nil { panic(err) } utils.FileLog.Info("end GetMP4Duration ") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) resp.PlaySeconds = duration br.Msg = "上传成功" br.Ret = 200 br.Success = true br.Data = resp utils.FileLog.Info("end VideoUpload ") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) return } // VoiceUpload // @Title 音频上传 // @Description 音频上传接口 // @Param file query file true "文件" // @Success 200 {object} models.ResourceResp // @router /voice/upload [post] func (this *ResourceController) VoiceUpload() { utils.FileLog.Info("start VoiceUpload ") utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime))) 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 } uploadFileName := h.Filename //上传的文件名 fileData, e := ioutil.ReadAll(f) if e != nil { br.Msg = "上传失败" br.ErrMsg = "读取文件失败, Err: " + e.Error() return } pass := filetype.IsAudio(fileData) if !pass { br.Msg = "文件格式有误" br.ErrMsg = "文件格式有误" return } ext := path.Ext(h.Filename) dateDir := time.Now().Format("20060102") uploadDir := utils.STATIC_DIR + "hongze/" + dateDir //uploadDir := "./" + dateDir fmt.Println(uploadDir) 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() //关闭上传文件 utils.FileLog.Info("start save") utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime))) utils.FileLog.Info(fmt.Sprintf("fpath %s:", fpath)) fileHandle, err := os.OpenFile(fpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755) if err != nil { br.Msg = "创建文件失败" br.ErrMsg = "创建文件失败,Err:" + err.Error() return } defer fileHandle.Close() localFileBuffer := make([]byte, 0) //循环读取 for { buffer := make([]byte, 4096) maxLen, err := f.Read(buffer) //如果错误信息是其他类型的,则直接panic if err != nil && err != io.EOF { br.Msg = "上传失败" br.ErrMsg = "读取文件内容失败,Err:" + err.Error() return } //注意,错误信息是以io包的EOF时,表示读取到文件末尾 if err == io.EOF { break } // NewWriter 默认缓冲区大小是 4096 // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法 buf := bufio.NewWriter(fileHandle) // 字节写入 // 字符串写入 buf.WriteString(string(buffer)) localFileBuffer = append(localFileBuffer, buffer[0:maxLen]...) // 将缓冲中的数据写入 err = buf.Flush() if err != nil { br.Msg = "上传失败" br.ErrMsg = "写入文件内容失败,Err:" + err.Error() return } } utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime))) utils.FileLog.Info("end save") defer func() { if utils.FileIsExist(fpath) { os.Remove(fpath) } }() var playSeconds float64 if ext == ".m4a" { //m4a格式的走这个计算逻辑 utils.FileLog.Info("start calculate m4a duration ") tmpPlaySeconds, err := services.GetMP4Duration(f) if err != nil { br.Msg = "音频资源时长计算失败" br.ErrMsg = "音频资源时长计算失败,Err:" + err.Error() return } playSeconds = float64(tmpPlaySeconds) utils.FileLog.Info("end calculate m4a duration ") } else { utils.FileLog.Info("start calculate mp3duration ") playSeconds, err = mp3duration.Calculate(fpath) if playSeconds <= 0 { playSeconds, err = utils.GetVideoPlaySeconds(fpath) if err != nil { br.Msg = "音频资源时长计算失败" br.ErrMsg = "音频资源时长计算失败,Err:" + err.Error() return } } utils.FileLog.Info("end calculate mp3duration ") } utils.FileLog.Info("start update oss ") utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime))) defer func() { _ = os.Remove(fpath) }() //savePath := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/") //savePath += fileName //上传到阿里云 和 minio resourceUrl := `` //if utils.ObjectStorageClient == "minio" { // err = services.UploadVideoToMinIo(fileName, fpath, savePath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } // resourceUrl = utils.MinIoImghost + savePath //} else { // err = services.UploadVideoAliyun(fileName, fpath, savePath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } // resourceUrl = utils.Imghost + savePath //} 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 } utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime))) utils.FileLog.Info("end update oss ") item := new(models.Resource) item.ResourceUrl = resourceUrl item.ResourceType = 3 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, PlaySeconds: uint32(playSeconds), } br.Msg = "上传成功" br.Ret = 200 br.Success = true br.Data = resp utils.FileLog.Info("end VoiceUpload ") utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime))) return } /* func (c *Controller) SaveToFile(fromfile, tofile string) error { file, _, err := c.Ctx.Request.FormFile(fromfile) if err != nil { return err } defer file.Close() 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, file) return nil } */ // @Title 上传图片 // @Description 上传图片 // @Param Image query string false "图片,base64字符串" // @Success 200 {object} models.ImageResponse // @router /upload_image_base64 [post] func (this *ResourceController) UploadImageBase64() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var err error ext := ".png" uploadDir := "./static" randStr := utils.GetRandStringNoSpecialChar(28) fileName := randStr + ext fpath := uploadDir + "/" + fileName image := this.Ctx.Request.FormValue("Image") if image == "" { // 从 file文件中获取 f, h, e := this.GetFile("Image") if e != nil { br.Msg = "参数错误" br.ErrMsg = "获取资源信息失败,Err:" + e.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 } 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("Image", fpath) if err != nil { br.Msg = "文件上传失败" br.ErrMsg = "文件上传失败,Err:" + err.Error() return } } else { b, _ := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, image) if !b { br.Msg = "图片格式不正确" br.ErrMsg = "图片格式不正确" return } re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`) base64Str := re.ReplaceAllString(image, "") base64Str = strings.Replace(base64Str, " ", "", -1) err = utils.SaveBase64ToFile(base64Str, fpath) if err != nil { br.Msg = "图片保存失败" br.ErrMsg = "图片保存失败,Err:" + err.Error() return } } fmt.Println("end") defer os.Remove(fpath) hzUploadDir := utils.RESOURCE_DIR + "images/" savePath := hzUploadDir + time.Now().Format("200601/20060102/") savePath += fileName //上传到阿里云 和 minio resourceUrl := `` //if utils.ObjectStorageClient == "minio" { // err = services.UploadFileToMinIo(fileName, fpath, savePath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } // resourceUrl = utils.MinIoImghost + savePath //} else { // err = services.UploadFileToAliyun(fileName, fpath, savePath) // if err != nil { // br.Msg = "文件上传失败" // br.ErrMsg = "文件上传失败,Err:" + err.Error() // return // } // resourceUrl = utils.Imghost + savePath //} ossClient := services.NewOssClient() if ossClient == nil { br.Msg = "上传失败" br.ErrMsg = "初始化OSS服务失败" return } resourceUrl, err = ossClient.UploadFile(fileName, fpath, savePath) if err != nil { br.Msg = "文件上传失败" br.ErrMsg = "文件上传失败,Err:" + err.Error() return } utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) utils.FileLog.Info("end update oss ") 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 utils.FileLog.Info("end VideoUpload ") utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime)) } // 判断文件是否存在 func IsFileExist(filename string) bool { _, err := os.Stat(filename) if os.IsNotExist(err) { return false } return true } // @Title 图片上传 // @Description 图片上传接口 // @Param file query file true "文件" // @Success 200 新增成功 // @router /image/uploadV2 [post] func (this *ResourceController) UploadV2() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() businessType := this.Ctx.Request.Form.Get("business_type") //this.Ctx.Request fmt.Println("businessType:", businessType) fmt.Println(this.Ctx.Request.Form) fmt.Println("===========") br.Data = businessType 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 } 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 := `` //上传到阿里云 和 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 // } //} 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 := new(models.ResourceResp) resp.Id = newId resp.ResourceUrl = resourceUrl br.Msg = "上传成功" br.Ret = 200 br.Success = true //br.Data = resp return } // @Title 获取STSToken // @Description 获取STSToken // @Success 200 获取成功 // @router /oss/get_sts_token [get] func (this *ResourceController) OssSTSToken() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() ossClient := services.NewOssClient() if ossClient == nil { br.Msg = "上传失败" br.ErrMsg = "初始化OSS服务失败" return } resp, e := ossClient.GetUploadToken() if e != nil { br.Msg = "获取失败" br.ErrMsg = "获取OSS上传Token失败, Err: " + e.Error() return } br.Data = resp br.Msg = "获取成功" br.Ret = 200 br.Success = true //source, _ := this.GetInt("StorageSource") // //if source == utils.STORAGESOURCE_OSS { // resp, err := services.GetOssSTSToken() // if err != nil { // br.Msg = "获取失败" // br.ErrMsg = "获取STSToken失败, Err: " + err.Error() // return // } // br.Data = resp // br.Msg = "获取成功" // br.Ret = 200 // br.Success = true //} else if source == utils.STORAGESOURCE_MINIO { // resp, err := services.GetMinIOSTSToken() // if err != nil { // br.Msg = "获取失败" // br.ErrMsg = "获取STSToken失败, Err: " + err.Error() // return // } // br.Data = resp // br.Msg = "获取成功" // br.Ret = 200 // br.Success = true //} } // FileDownload // @Title 文件下载 // @Description 文件下载 // @Param FileUrl query string true "文件路径" // @Success 200 Ret=200 操作成功 // @router /file/download [get] func (this *ResourceAuthController) FileDownload() { br := new(models.BaseResponse).Init() defer func() { if br.ErrMsg == "" { br.IsSendEmail = false } this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请登录" br.ErrMsg = "请登录,SysUser Is Empty" br.Ret = 408 return } //fileName := this.GetString("FileName") //fileName = strings.TrimSpace(fileName) //if fileName == "" { // br.Msg = "参数有误" // return //} fileEncode := this.GetString("FileUrl") fileEncode = strings.TrimSpace(fileEncode) if fileEncode == "" { br.Msg = "参数有误" return } fileByte, e := base64.StdEncoding.DecodeString(fileEncode) if e != nil { br.Msg = "下载失败" br.ErrMsg = "文件地址解析失败, Err: " + e.Error() return } fileUrl := string(fileByte) fileArr := strings.Split(fileUrl, "/") if len(fileArr) == 0 { br.Msg = "文件地址有误" return } fileName := fileArr[len(fileArr)-1] //fmt.Println(fileName) // 获取文件 down, e := http.Get(fileUrl) if e != nil { br.Msg = "下载失败" br.ErrMsg = "文件下载失败, http get: " + e.Error() return } defer down.Body.Close() if down.StatusCode != http.StatusOK { br.Msg = "下载失败" br.ErrMsg = fmt.Sprintf("文件下载失败, http status: %d", down.StatusCode) return } // 生成本地文件 localFilePath := fmt.Sprintf("%s%s", utils.GetRandStringNoSpecialChar(6), fileName) localFile, e := os.Create(localFilePath) if e != nil { br.Msg = "下载失败" br.ErrMsg = "生成本地文件失败, Err: " + e.Error() return } defer func() { if e = localFile.Close(); e != nil { fmt.Println("local file close err: ", e.Error()) } if e = os.Remove(localFilePath); e != nil { fmt.Println("local file remove err: ", e.Error()) } }() // 写入响应流 //_, e = io.Copy(this.Ctx.ResponseWriter, down.Body) _, e = io.Copy(localFile, down.Body) if e != nil { br.Msg = "下载失败" br.ErrMsg = "复制文件资源失败, Err: " + e.Error() return } // 设置响应头 //this.Ctx.ResponseWriter.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName)) //this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/octet-stream") br.Ret = 200 br.Msg = "下载成功" br.Success = true this.Ctx.Output.Download(localFilePath, fileName) } // FileDownload // @Title 文件加载 // @Description 文件加载 // @Param FileUrl query string true "文件路径" // @Success 200 Ret=200 操作成功 // @router /file/reload [get] func (this *ResourceController) FileReload() { fileUrl := `https://hzstatic.hzinsights.com/static/images/202202/20220208/Qr3dulOoVTJgyl8skH1jL1kv36RX.png` body, err := rdHttp.Get(fileUrl) if err != nil { fmt.Println("err: ", err) this.Ctx.WriteString("err: " + err.Error() + "") return } // 设置响应头 this.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png") this.Ctx.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(len(body))) // 将文件内容写入响应体 _, err = this.Ctx.ResponseWriter.Write(body) if err != nil { http.Error(this.Ctx.ResponseWriter, "Failed to write response", http.StatusInternalServerError) return } }