resource.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. package controllers
  2. import (
  3. "bufio"
  4. "encoding/base64"
  5. "eta_gn/eta_api/models"
  6. "eta_gn/eta_api/services"
  7. "eta_gn/eta_api/utils"
  8. "fmt"
  9. "github.com/h2non/filetype"
  10. "github.com/kgiannakakis/mp3duration/src/mp3duration"
  11. "io"
  12. "io/ioutil"
  13. "net/http"
  14. "os"
  15. "path"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "time"
  20. rdHttp "github.com/rdlucklib/rdluck_tools/http"
  21. )
  22. // 资源管理-图片上传,合同上传等
  23. type ResourceController struct {
  24. //BaseAuthController
  25. BaseCommonController
  26. }
  27. // ResourceAuthController 文件资源
  28. type ResourceAuthController struct {
  29. BaseAuthController
  30. }
  31. // @Title 图片上传
  32. // @Description 图片上传接口
  33. // @Param file query file true "文件"
  34. // @Success 200 {object} models.ResourceResp
  35. // @router /image/upload [post]
  36. func (this *ResourceController) Upload() {
  37. br := new(models.BaseResponse).Init()
  38. defer func() {
  39. this.Data["json"] = br
  40. this.ServeJSON()
  41. }()
  42. f, h, err := this.GetFile("file")
  43. if err != nil {
  44. br.Msg = "获取资源信息失败"
  45. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  46. return
  47. }
  48. fileData, e := ioutil.ReadAll(f)
  49. if e != nil {
  50. br.Msg = "上传失败"
  51. br.ErrMsg = "读取文件失败, Err: " + e.Error()
  52. return
  53. }
  54. pass := filetype.IsImage(fileData)
  55. if !pass {
  56. br.Msg = "文件格式有误"
  57. br.ErrMsg = "文件格式有误"
  58. return
  59. }
  60. uploadFileName := h.Filename //上传的文件名
  61. ext := path.Ext(h.Filename)
  62. dateDir := time.Now().Format("20060102")
  63. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  64. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  65. if err != nil {
  66. br.Msg = "存储目录创建失败"
  67. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  68. return
  69. }
  70. randStr := utils.GetRandStringNoSpecialChar(28)
  71. fileName := randStr + ext
  72. fpath := uploadDir + "/" + fileName
  73. defer f.Close() //关闭上传文件
  74. err = this.SaveToFile("file", fpath)
  75. if err != nil {
  76. br.Msg = "文件上传失败"
  77. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  78. return
  79. }
  80. resourceUrl := ``
  81. //上传到阿里云 和 minio
  82. //if utils.ObjectStorageClient == "minio" {
  83. // resourceUrl, err = services.UploadImgToMinIo(fileName, fpath)
  84. // if err != nil {
  85. // br.Msg = "文件上传失败"
  86. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  87. // return
  88. // }
  89. //} else {
  90. // resourceUrl, err = services.UploadAliyunV2(fileName, fpath)
  91. // if err != nil {
  92. // br.Msg = "文件上传失败"
  93. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  94. // return
  95. // }
  96. //}
  97. ossClient := services.NewOssClient()
  98. if ossClient == nil {
  99. br.Msg = "上传失败"
  100. br.ErrMsg = "初始化OSS服务失败"
  101. return
  102. }
  103. resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
  104. if err != nil {
  105. br.Msg = "文件上传失败"
  106. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  107. return
  108. }
  109. defer func() {
  110. os.Remove(fpath)
  111. }()
  112. item := new(models.Resource)
  113. item.ResourceUrl = resourceUrl
  114. item.ResourceType = 1
  115. item.CreateTime = time.Now()
  116. newId, err := models.AddResource(item)
  117. if err != nil {
  118. br.Msg = "资源上传失败"
  119. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  120. return
  121. }
  122. resp := models.ResourceResp{
  123. Id: newId,
  124. ResourceUrl: resourceUrl,
  125. ResourceName: uploadFileName,
  126. }
  127. br.Msg = "上传成功"
  128. br.Ret = 200
  129. br.Success = true
  130. br.Data = resp
  131. return
  132. }
  133. // @Title 视频上传
  134. // @Description 视频上传接口
  135. // @Param file query file true "文件"
  136. // @Success 200 新增成功
  137. // @router /video/upload [post]
  138. func (this *ResourceController) VideoUpload() {
  139. utils.FileLog.Info("start VideoUpload ")
  140. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  141. br := new(models.BaseResponse).Init()
  142. defer func() {
  143. this.Data["json"] = br
  144. this.ServeJSON()
  145. }()
  146. f, h, err := this.GetFile("file")
  147. if err != nil {
  148. br.Msg = "获取资源信息失败"
  149. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  150. return
  151. }
  152. fileData, e := ioutil.ReadAll(f)
  153. if e != nil {
  154. br.Msg = "上传失败"
  155. br.ErrMsg = "读取文件失败, Err: " + e.Error()
  156. return
  157. }
  158. pass := filetype.IsVideo(fileData)
  159. if !pass {
  160. br.Msg = "文件格式有误"
  161. br.ErrMsg = "文件格式有误"
  162. return
  163. }
  164. ext := path.Ext(h.Filename)
  165. dateDir := time.Now().Format("20060102")
  166. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  167. //uploadDir := "./" + dateDir
  168. fmt.Println(uploadDir)
  169. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  170. if err != nil {
  171. br.Msg = "存储目录创建失败"
  172. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  173. return
  174. }
  175. randStr := utils.GetRandStringNoSpecialChar(28)
  176. fileName := randStr + ext
  177. fpath := uploadDir + "/" + fileName
  178. defer f.Close() //关闭上传文件
  179. utils.FileLog.Info("start save")
  180. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  181. utils.FileLog.Info("fpath %s:", fpath)
  182. fileHandle, err := os.OpenFile(fpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModeAppend)
  183. if err != nil {
  184. br.Msg = "创建文件失败"
  185. br.ErrMsg = "创建文件失败,Err:" + err.Error()
  186. return
  187. }
  188. defer fileHandle.Close()
  189. //循环读取
  190. for {
  191. buffer := make([]byte, 4096)
  192. _, err := f.Read(buffer)
  193. //如果错误信息是其他类型的,则直接panic
  194. if err != nil && err != io.EOF {
  195. br.Msg = "上传失败"
  196. br.ErrMsg = "读取文件内容失败,Err:" + err.Error()
  197. return
  198. }
  199. //注意,错误信息是以io包的EOF时,表示读取到文件末尾
  200. if err == io.EOF {
  201. break
  202. }
  203. // NewWriter 默认缓冲区大小是 4096
  204. // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法
  205. buf := bufio.NewWriter(fileHandle)
  206. // 字节写入
  207. // 字符串写入
  208. buf.WriteString(string(buffer))
  209. // 将缓冲中的数据写入
  210. err = buf.Flush()
  211. if err != nil {
  212. br.Msg = "上传失败"
  213. br.ErrMsg = "写入文件内容失败,Err:" + err.Error()
  214. return
  215. }
  216. }
  217. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  218. utils.FileLog.Info("end save")
  219. //err = this.SaveToFile("file", fpath)
  220. //if err != nil {
  221. // br.Msg = "文件上传失败"
  222. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  223. // return
  224. //}
  225. /*
  226. fmt.Println("start")
  227. fmt.Println(time.Now())
  228. tofile:="./20201123.mp4"
  229. fromFile:="./第五期下.mp4"
  230. f, err := os.Open(fromFile)
  231. defer f.Close() //注意要关闭文件
  232. fileHandle, err := os.OpenFile(tofile, os.O_RDONLY|os.O_CREATE|os.O_APPEND, 0666)
  233. if err != nil {
  234. fmt.Println("open file error :", err)
  235. return
  236. }
  237. defer fileHandle.Close()
  238. if err != nil {
  239. panic(err)
  240. } else {
  241. //循环读取
  242. for {
  243. buffer := make([]byte, 4096)
  244. _, err := f.Read(buffer)
  245. //如果错误信息是其他类型的,则直接panic
  246. if err != nil && err != io.EOF {
  247. panic(err)
  248. }
  249. //注意,错误信息是以io包的EOF时,表示读取到文件末尾
  250. if err == io.EOF {
  251. fmt.Println("读取完毕")
  252. break
  253. }
  254. // NewWriter 默认缓冲区大小是 4096
  255. // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法
  256. buf := bufio.NewWriter(fileHandle)
  257. // 字节写入
  258. // 字符串写入
  259. buf.WriteString(string(buffer))
  260. // 将缓冲中的数据写入
  261. err = buf.Flush()
  262. if err != nil {
  263. fmt.Println("flush error :"+err.Error())
  264. return
  265. }
  266. }
  267. }
  268. */
  269. utils.FileLog.Info("start update oss ")
  270. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  271. //savePath := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  272. //savePath += fileName
  273. defer func() {
  274. _ = os.Remove(fpath)
  275. }()
  276. //上传到阿里云 和 minio
  277. resourceUrl := ``
  278. //if utils.ObjectStorageClient == "minio" {
  279. // err = services.UploadVideoToMinIo(fileName, fpath, savePath)
  280. // if err != nil {
  281. // br.Msg = "文件上传失败"
  282. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  283. // return
  284. // }
  285. // resourceUrl = utils.MinIoImghost + savePath
  286. //} else {
  287. // err = services.UploadVideoAliyun(fileName, fpath, savePath)
  288. // if err != nil {
  289. // br.Msg = "文件上传失败"
  290. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  291. // return
  292. // }
  293. // resourceUrl = utils.Imghost + savePath
  294. //}
  295. ossClient := services.NewOssClient()
  296. if ossClient == nil {
  297. br.Msg = "上传失败"
  298. br.ErrMsg = "初始化OSS服务失败"
  299. return
  300. }
  301. resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
  302. if err != nil {
  303. br.Msg = "文件上传失败"
  304. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  305. return
  306. }
  307. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  308. utils.FileLog.Info("end update oss ")
  309. item := new(models.Resource)
  310. item.ResourceUrl = resourceUrl
  311. item.ResourceType = 3
  312. item.CreateTime = time.Now()
  313. newId, err := models.AddResource(item)
  314. if err != nil {
  315. br.Msg = "资源上传失败"
  316. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  317. return
  318. }
  319. resp := new(models.ResourceResp)
  320. resp.Id = newId
  321. resp.ResourceUrl = resourceUrl
  322. utils.FileLog.Info("start GetMP4Duration ")
  323. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  324. duration, err := services.GetMP4Duration(f)
  325. if err != nil {
  326. panic(err)
  327. }
  328. utils.FileLog.Info("end GetMP4Duration ")
  329. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  330. resp.PlaySeconds = duration
  331. br.Msg = "上传成功"
  332. br.Ret = 200
  333. br.Success = true
  334. br.Data = resp
  335. utils.FileLog.Info("end VideoUpload ")
  336. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  337. return
  338. }
  339. // VoiceUpload
  340. // @Title 音频上传
  341. // @Description 音频上传接口
  342. // @Param file query file true "文件"
  343. // @Success 200 {object} models.ResourceResp
  344. // @router /voice/upload [post]
  345. func (this *ResourceController) VoiceUpload() {
  346. utils.FileLog.Info("start VoiceUpload ")
  347. utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime)))
  348. br := new(models.BaseResponse).Init()
  349. defer func() {
  350. this.Data["json"] = br
  351. this.ServeJSON()
  352. }()
  353. f, h, err := this.GetFile("file")
  354. if err != nil {
  355. br.Msg = "获取资源信息失败"
  356. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  357. return
  358. }
  359. uploadFileName := h.Filename //上传的文件名
  360. fileData, e := ioutil.ReadAll(f)
  361. if e != nil {
  362. br.Msg = "上传失败"
  363. br.ErrMsg = "读取文件失败, Err: " + e.Error()
  364. return
  365. }
  366. pass := filetype.IsAudio(fileData)
  367. if !pass {
  368. br.Msg = "文件格式有误"
  369. br.ErrMsg = "文件格式有误"
  370. return
  371. }
  372. ext := path.Ext(h.Filename)
  373. dateDir := time.Now().Format("20060102")
  374. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  375. //uploadDir := "./" + dateDir
  376. fmt.Println(uploadDir)
  377. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  378. if err != nil {
  379. br.Msg = "存储目录创建失败"
  380. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  381. return
  382. }
  383. randStr := utils.GetRandStringNoSpecialChar(28)
  384. fileName := randStr + ext
  385. fpath := uploadDir + "/" + fileName
  386. defer f.Close() //关闭上传文件
  387. utils.FileLog.Info("start save")
  388. utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime)))
  389. utils.FileLog.Info(fmt.Sprintf("fpath %s:", fpath))
  390. fileHandle, err := os.OpenFile(fpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
  391. if err != nil {
  392. br.Msg = "创建文件失败"
  393. br.ErrMsg = "创建文件失败,Err:" + err.Error()
  394. return
  395. }
  396. defer fileHandle.Close()
  397. localFileBuffer := make([]byte, 0)
  398. //循环读取
  399. for {
  400. buffer := make([]byte, 4096)
  401. maxLen, err := f.Read(buffer)
  402. //如果错误信息是其他类型的,则直接panic
  403. if err != nil && err != io.EOF {
  404. br.Msg = "上传失败"
  405. br.ErrMsg = "读取文件内容失败,Err:" + err.Error()
  406. return
  407. }
  408. //注意,错误信息是以io包的EOF时,表示读取到文件末尾
  409. if err == io.EOF {
  410. break
  411. }
  412. // NewWriter 默认缓冲区大小是 4096
  413. // 需要使用自定义缓冲区的writer 使用 NewWriterSize()方法
  414. buf := bufio.NewWriter(fileHandle)
  415. // 字节写入
  416. // 字符串写入
  417. buf.WriteString(string(buffer))
  418. localFileBuffer = append(localFileBuffer, buffer[0:maxLen]...)
  419. // 将缓冲中的数据写入
  420. err = buf.Flush()
  421. if err != nil {
  422. br.Msg = "上传失败"
  423. br.ErrMsg = "写入文件内容失败,Err:" + err.Error()
  424. return
  425. }
  426. }
  427. utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime)))
  428. utils.FileLog.Info("end save")
  429. defer func() {
  430. if utils.FileIsExist(fpath) {
  431. os.Remove(fpath)
  432. }
  433. }()
  434. var playSeconds float64
  435. if ext == ".m4a" { //m4a格式的走这个计算逻辑
  436. utils.FileLog.Info("start calculate m4a duration ")
  437. tmpPlaySeconds, err := services.GetMP4Duration(f)
  438. if err != nil {
  439. br.Msg = "音频资源时长计算失败"
  440. br.ErrMsg = "音频资源时长计算失败,Err:" + err.Error()
  441. return
  442. }
  443. playSeconds = float64(tmpPlaySeconds)
  444. utils.FileLog.Info("end calculate m4a duration ")
  445. } else {
  446. utils.FileLog.Info("start calculate mp3duration ")
  447. playSeconds, err = mp3duration.Calculate(fpath)
  448. if playSeconds <= 0 {
  449. playSeconds, err = utils.GetVideoPlaySeconds(fpath)
  450. if err != nil {
  451. br.Msg = "音频资源时长计算失败"
  452. br.ErrMsg = "音频资源时长计算失败,Err:" + err.Error()
  453. return
  454. }
  455. }
  456. utils.FileLog.Info("end calculate mp3duration ")
  457. }
  458. utils.FileLog.Info("start update oss ")
  459. utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime)))
  460. defer func() {
  461. _ = os.Remove(fpath)
  462. }()
  463. //savePath := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  464. //savePath += fileName
  465. //上传到阿里云 和 minio
  466. resourceUrl := ``
  467. //if utils.ObjectStorageClient == "minio" {
  468. // err = services.UploadVideoToMinIo(fileName, fpath, savePath)
  469. // if err != nil {
  470. // br.Msg = "文件上传失败"
  471. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  472. // return
  473. // }
  474. // resourceUrl = utils.MinIoImghost + savePath
  475. //} else {
  476. // err = services.UploadVideoAliyun(fileName, fpath, savePath)
  477. // if err != nil {
  478. // br.Msg = "文件上传失败"
  479. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  480. // return
  481. // }
  482. // resourceUrl = utils.Imghost + savePath
  483. //}
  484. ossClient := services.NewOssClient()
  485. if ossClient == nil {
  486. br.Msg = "上传失败"
  487. br.ErrMsg = "初始化OSS服务失败"
  488. return
  489. }
  490. resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
  491. if err != nil {
  492. br.Msg = "文件上传失败"
  493. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  494. return
  495. }
  496. utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime)))
  497. utils.FileLog.Info("end update oss ")
  498. item := new(models.Resource)
  499. item.ResourceUrl = resourceUrl
  500. item.ResourceType = 3
  501. item.CreateTime = time.Now()
  502. newId, err := models.AddResource(item)
  503. if err != nil {
  504. br.Msg = "音频资源上传失败"
  505. br.ErrMsg = "音频资源上传失败,Err:" + err.Error()
  506. return
  507. }
  508. resp := models.ResourceResp{
  509. Id: newId,
  510. ResourceUrl: resourceUrl,
  511. ResourceName: uploadFileName,
  512. PlaySeconds: uint32(playSeconds),
  513. }
  514. br.Msg = "上传成功"
  515. br.Ret = 200
  516. br.Success = true
  517. br.Data = resp
  518. utils.FileLog.Info("end VoiceUpload ")
  519. utils.FileLog.Info(fmt.Sprintf("%s:", time.Now().Format(utils.FormatDateTime)))
  520. return
  521. }
  522. /*
  523. func (c *Controller) SaveToFile(fromfile, tofile string) error {
  524. file, _, err := c.Ctx.Request.FormFile(fromfile)
  525. if err != nil {
  526. return err
  527. }
  528. defer file.Close()
  529. f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
  530. if err != nil {
  531. return err
  532. }
  533. defer f.Close()
  534. io.Copy(f, file)
  535. return nil
  536. }
  537. */
  538. // @Title 上传图片
  539. // @Description 上传图片
  540. // @Param Image query string false "图片,base64字符串"
  541. // @Success 200 {object} models.ImageResponse
  542. // @router /upload_image_base64 [post]
  543. func (this *ResourceController) UploadImageBase64() {
  544. br := new(models.BaseResponse).Init()
  545. defer func() {
  546. this.Data["json"] = br
  547. this.ServeJSON()
  548. }()
  549. var err error
  550. ext := ".png"
  551. uploadDir := "./static"
  552. randStr := utils.GetRandStringNoSpecialChar(28)
  553. fileName := randStr + ext
  554. fpath := uploadDir + "/" + fileName
  555. image := this.Ctx.Request.FormValue("Image")
  556. if image == "" {
  557. // 从 file文件中获取
  558. f, h, e := this.GetFile("Image")
  559. if e != nil {
  560. br.Msg = "参数错误"
  561. br.ErrMsg = "获取资源信息失败,Err:" + e.Error()
  562. return
  563. }
  564. fileData, e := ioutil.ReadAll(f)
  565. if e != nil {
  566. br.Msg = "上传失败"
  567. br.ErrMsg = "读取文件失败, Err: " + e.Error()
  568. return
  569. }
  570. pass := filetype.IsImage(fileData)
  571. if !pass {
  572. br.Msg = "文件格式有误"
  573. br.ErrMsg = "文件格式有误"
  574. return
  575. }
  576. ext = path.Ext(h.Filename)
  577. dateDir := time.Now().Format("20060102")
  578. uploadDir = utils.STATIC_DIR + "hongze/" + dateDir
  579. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  580. if err != nil {
  581. br.Msg = "存储目录创建失败"
  582. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  583. return
  584. }
  585. randStr = utils.GetRandStringNoSpecialChar(28)
  586. fileName = randStr + ext
  587. fpath = uploadDir + "/" + fileName
  588. defer f.Close() //关闭上传文件
  589. err = this.SaveToFile("Image", fpath)
  590. if err != nil {
  591. br.Msg = "文件上传失败"
  592. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  593. return
  594. }
  595. } else {
  596. b, _ := regexp.MatchString(`^data:\s*image\/(\w+);base64,`, image)
  597. if !b {
  598. br.Msg = "图片格式不正确"
  599. br.ErrMsg = "图片格式不正确"
  600. return
  601. }
  602. re, _ := regexp.Compile(`^data:\s*image\/(\w+);base64,`)
  603. base64Str := re.ReplaceAllString(image, "")
  604. base64Str = strings.Replace(base64Str, " ", "", -1)
  605. err = utils.SaveBase64ToFile(base64Str, fpath)
  606. if err != nil {
  607. br.Msg = "图片保存失败"
  608. br.ErrMsg = "图片保存失败,Err:" + err.Error()
  609. return
  610. }
  611. }
  612. fmt.Println("end")
  613. defer os.Remove(fpath)
  614. hzUploadDir := utils.RESOURCE_DIR + "images/"
  615. savePath := hzUploadDir + time.Now().Format("200601/20060102/")
  616. savePath += fileName
  617. //上传到阿里云 和 minio
  618. resourceUrl := ``
  619. //if utils.ObjectStorageClient == "minio" {
  620. // err = services.UploadFileToMinIo(fileName, fpath, savePath)
  621. // if err != nil {
  622. // br.Msg = "文件上传失败"
  623. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  624. // return
  625. // }
  626. // resourceUrl = utils.MinIoImghost + savePath
  627. //} else {
  628. // err = services.UploadFileToAliyun(fileName, fpath, savePath)
  629. // if err != nil {
  630. // br.Msg = "文件上传失败"
  631. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  632. // return
  633. // }
  634. // resourceUrl = utils.Imghost + savePath
  635. //}
  636. ossClient := services.NewOssClient()
  637. if ossClient == nil {
  638. br.Msg = "上传失败"
  639. br.ErrMsg = "初始化OSS服务失败"
  640. return
  641. }
  642. resourceUrl, err = ossClient.UploadFile(fileName, fpath, savePath)
  643. if err != nil {
  644. br.Msg = "文件上传失败"
  645. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  646. return
  647. }
  648. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  649. utils.FileLog.Info("end update oss ")
  650. item := new(models.Resource)
  651. item.ResourceUrl = resourceUrl
  652. item.ResourceType = 1
  653. item.CreateTime = time.Now()
  654. newId, err := models.AddResource(item)
  655. if err != nil {
  656. br.Msg = "资源上传失败"
  657. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  658. return
  659. }
  660. resp := new(models.ResourceResp)
  661. resp.Id = newId
  662. resp.ResourceUrl = resourceUrl
  663. br.Msg = "上传成功"
  664. br.Ret = 200
  665. br.Success = true
  666. br.Data = resp
  667. utils.FileLog.Info("end VideoUpload ")
  668. utils.FileLog.Info("%s:", time.Now().Format(utils.FormatDateTime))
  669. }
  670. // 判断文件是否存在
  671. func IsFileExist(filename string) bool {
  672. _, err := os.Stat(filename)
  673. if os.IsNotExist(err) {
  674. return false
  675. }
  676. return true
  677. }
  678. // @Title 图片上传
  679. // @Description 图片上传接口
  680. // @Param file query file true "文件"
  681. // @Success 200 新增成功
  682. // @router /image/uploadV2 [post]
  683. func (this *ResourceController) UploadV2() {
  684. br := new(models.BaseResponse).Init()
  685. defer func() {
  686. this.Data["json"] = br
  687. this.ServeJSON()
  688. }()
  689. businessType := this.Ctx.Request.Form.Get("business_type")
  690. //this.Ctx.Request
  691. fmt.Println("businessType:", businessType)
  692. fmt.Println(this.Ctx.Request.Form)
  693. fmt.Println("===========")
  694. br.Data = businessType
  695. f, h, err := this.GetFile("file")
  696. if err != nil {
  697. br.Msg = "获取资源信息失败"
  698. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  699. return
  700. }
  701. fileData, e := ioutil.ReadAll(f)
  702. if e != nil {
  703. br.Msg = "上传失败"
  704. br.ErrMsg = "读取文件失败, Err: " + e.Error()
  705. return
  706. }
  707. pass := filetype.IsImage(fileData)
  708. if !pass {
  709. br.Msg = "文件格式有误"
  710. br.ErrMsg = "文件格式有误"
  711. return
  712. }
  713. ext := path.Ext(h.Filename)
  714. dateDir := time.Now().Format("20060102")
  715. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  716. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  717. if err != nil {
  718. br.Msg = "存储目录创建失败"
  719. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  720. return
  721. }
  722. randStr := utils.GetRandStringNoSpecialChar(28)
  723. fileName := randStr + ext
  724. fpath := uploadDir + "/" + fileName
  725. defer f.Close() //关闭上传文件
  726. err = this.SaveToFile("file", fpath)
  727. if err != nil {
  728. br.Msg = "文件上传失败"
  729. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  730. return
  731. }
  732. resourceUrl := ``
  733. //上传到阿里云 和 minio
  734. //if utils.ObjectStorageClient == "minio" {
  735. // resourceUrl, err = services.UploadImgToMinIo(fileName, fpath)
  736. // if err != nil {
  737. // br.Msg = "文件上传失败"
  738. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  739. // return
  740. // }
  741. //} else {
  742. // resourceUrl, err = services.UploadAliyunV2(fileName, fpath)
  743. // if err != nil {
  744. // br.Msg = "文件上传失败"
  745. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  746. // return
  747. // }
  748. //}
  749. ossClient := services.NewOssClient()
  750. if ossClient == nil {
  751. br.Msg = "上传失败"
  752. br.ErrMsg = "初始化OSS服务失败"
  753. return
  754. }
  755. resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
  756. if err != nil {
  757. br.Msg = "文件上传失败"
  758. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  759. return
  760. }
  761. defer func() {
  762. os.Remove(fpath)
  763. }()
  764. item := new(models.Resource)
  765. item.ResourceUrl = resourceUrl
  766. item.ResourceType = 1
  767. item.CreateTime = time.Now()
  768. newId, err := models.AddResource(item)
  769. if err != nil {
  770. br.Msg = "资源上传失败"
  771. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  772. return
  773. }
  774. resp := new(models.ResourceResp)
  775. resp.Id = newId
  776. resp.ResourceUrl = resourceUrl
  777. br.Msg = "上传成功"
  778. br.Ret = 200
  779. br.Success = true
  780. //br.Data = resp
  781. return
  782. }
  783. // @Title 获取STSToken
  784. // @Description 获取STSToken
  785. // @Success 200 获取成功
  786. // @router /oss/get_sts_token [get]
  787. func (this *ResourceController) OssSTSToken() {
  788. br := new(models.BaseResponse).Init()
  789. defer func() {
  790. this.Data["json"] = br
  791. this.ServeJSON()
  792. }()
  793. ossClient := services.NewOssClient()
  794. if ossClient == nil {
  795. br.Msg = "上传失败"
  796. br.ErrMsg = "初始化OSS服务失败"
  797. return
  798. }
  799. resp, e := ossClient.GetUploadToken()
  800. if e != nil {
  801. br.Msg = "获取失败"
  802. br.ErrMsg = "获取OSS上传Token失败, Err: " + e.Error()
  803. return
  804. }
  805. br.Data = resp
  806. br.Msg = "获取成功"
  807. br.Ret = 200
  808. br.Success = true
  809. //source, _ := this.GetInt("StorageSource")
  810. //
  811. //if source == utils.STORAGESOURCE_OSS {
  812. // resp, err := services.GetOssSTSToken()
  813. // if err != nil {
  814. // br.Msg = "获取失败"
  815. // br.ErrMsg = "获取STSToken失败, Err: " + err.Error()
  816. // return
  817. // }
  818. // br.Data = resp
  819. // br.Msg = "获取成功"
  820. // br.Ret = 200
  821. // br.Success = true
  822. //} else if source == utils.STORAGESOURCE_MINIO {
  823. // resp, err := services.GetMinIOSTSToken()
  824. // if err != nil {
  825. // br.Msg = "获取失败"
  826. // br.ErrMsg = "获取STSToken失败, Err: " + err.Error()
  827. // return
  828. // }
  829. // br.Data = resp
  830. // br.Msg = "获取成功"
  831. // br.Ret = 200
  832. // br.Success = true
  833. //}
  834. }
  835. // FileDownload
  836. // @Title 文件下载
  837. // @Description 文件下载
  838. // @Param FileUrl query string true "文件路径"
  839. // @Success 200 Ret=200 操作成功
  840. // @router /file/download [get]
  841. func (this *ResourceAuthController) FileDownload() {
  842. br := new(models.BaseResponse).Init()
  843. defer func() {
  844. if br.ErrMsg == "" {
  845. br.IsSendEmail = false
  846. }
  847. this.Data["json"] = br
  848. this.ServeJSON()
  849. }()
  850. sysUser := this.SysUser
  851. if sysUser == nil {
  852. br.Msg = "请登录"
  853. br.ErrMsg = "请登录,SysUser Is Empty"
  854. br.Ret = 408
  855. return
  856. }
  857. //fileName := this.GetString("FileName")
  858. //fileName = strings.TrimSpace(fileName)
  859. //if fileName == "" {
  860. // br.Msg = "参数有误"
  861. // return
  862. //}
  863. fileEncode := this.GetString("FileUrl")
  864. fileEncode = strings.TrimSpace(fileEncode)
  865. if fileEncode == "" {
  866. br.Msg = "参数有误"
  867. return
  868. }
  869. fileByte, e := base64.StdEncoding.DecodeString(fileEncode)
  870. if e != nil {
  871. br.Msg = "下载失败"
  872. br.ErrMsg = "文件地址解析失败, Err: " + e.Error()
  873. return
  874. }
  875. fileUrl := string(fileByte)
  876. fileArr := strings.Split(fileUrl, "/")
  877. if len(fileArr) == 0 {
  878. br.Msg = "文件地址有误"
  879. return
  880. }
  881. fileName := fileArr[len(fileArr)-1]
  882. //fmt.Println(fileName)
  883. // 获取文件
  884. down, e := http.Get(fileUrl)
  885. if e != nil {
  886. br.Msg = "下载失败"
  887. br.ErrMsg = "文件下载失败, http get: " + e.Error()
  888. return
  889. }
  890. defer down.Body.Close()
  891. if down.StatusCode != http.StatusOK {
  892. br.Msg = "下载失败"
  893. br.ErrMsg = fmt.Sprintf("文件下载失败, http status: %d", down.StatusCode)
  894. return
  895. }
  896. // 生成本地文件
  897. localFilePath := fmt.Sprintf("%s%s", utils.GetRandStringNoSpecialChar(6), fileName)
  898. localFile, e := os.Create(localFilePath)
  899. if e != nil {
  900. br.Msg = "下载失败"
  901. br.ErrMsg = "生成本地文件失败, Err: " + e.Error()
  902. return
  903. }
  904. defer func() {
  905. if e = localFile.Close(); e != nil {
  906. fmt.Println("local file close err: ", e.Error())
  907. }
  908. if e = os.Remove(localFilePath); e != nil {
  909. fmt.Println("local file remove err: ", e.Error())
  910. }
  911. }()
  912. // 写入响应流
  913. //_, e = io.Copy(this.Ctx.ResponseWriter, down.Body)
  914. _, e = io.Copy(localFile, down.Body)
  915. if e != nil {
  916. br.Msg = "下载失败"
  917. br.ErrMsg = "复制文件资源失败, Err: " + e.Error()
  918. return
  919. }
  920. // 设置响应头
  921. //this.Ctx.ResponseWriter.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
  922. //this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/octet-stream")
  923. br.Ret = 200
  924. br.Msg = "下载成功"
  925. br.Success = true
  926. this.Ctx.Output.Download(localFilePath, fileName)
  927. }
  928. // FileDownload
  929. // @Title 文件加载
  930. // @Description 文件加载
  931. // @Param FileUrl query string true "文件路径"
  932. // @Success 200 Ret=200 操作成功
  933. // @router /file/reload [get]
  934. func (this *ResourceController) FileReload() {
  935. fileUrl := `https://hzstatic.hzinsights.com/static/images/202202/20220208/Qr3dulOoVTJgyl8skH1jL1kv36RX.png`
  936. body, err := rdHttp.Get(fileUrl)
  937. if err != nil {
  938. fmt.Println("err: ", err)
  939. this.Ctx.WriteString("err: " + err.Error() + "")
  940. return
  941. }
  942. // 设置响应头
  943. this.Ctx.ResponseWriter.Header().Set("Content-Type", "image/png")
  944. this.Ctx.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(len(body)))
  945. // 将文件内容写入响应体
  946. _, err = this.Ctx.ResponseWriter.Write(body)
  947. if err != nil {
  948. http.Error(this.Ctx.ResponseWriter, "Failed to write response", http.StatusInternalServerError)
  949. return
  950. }
  951. }