1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027 |
- 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
- }
- }
|