sys_attachment_api.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. package client
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/druidcaesa/gotool"
  6. "github.com/qiniu/go-sdk/v7/auth/qbox"
  7. "github.com/qiniu/go-sdk/v7/storage"
  8. "image"
  9. "image/jpeg"
  10. "image/png"
  11. "io"
  12. "log"
  13. "os"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "ulink-admin/config"
  18. "ulink-admin/frame"
  19. "ulink-admin/modules/system/models/model"
  20. "ulink-admin/modules/system/models/req"
  21. "ulink-admin/modules/system/models/response"
  22. "ulink-admin/modules/system/service"
  23. "ulink-admin/pkg/excels"
  24. "ulink-admin/pkg/file"
  25. "ulink-admin/pkg/jwt/admin"
  26. "ulink-admin/pkg/page"
  27. "ulink-admin/pkg/tool"
  28. )
  29. type SysAttachmentApi struct {
  30. SysAttachmentService *service.SysAttachmentService `inject:""`
  31. }
  32. // List 查询附件分页数据
  33. func (a SysAttachmentApi) List(c *frame.Context) {
  34. query := &req.SysAttachmentQuery{}
  35. c.ValidteError(c.ShouldBind(query), query)
  36. list, i := a.SysAttachmentService.FindList(query)
  37. c.Ok(page.Page{
  38. List: list,
  39. Total: i,
  40. Size: query.PageSize,
  41. })
  42. }
  43. // List 查询附件所有数据
  44. func (a SysAttachmentApi) ListAll(c *frame.Context) {
  45. list := a.SysAttachmentService.FindAll()
  46. c.Ok(list)
  47. }
  48. // Get 根据附件Id获取详细信息
  49. func (a SysAttachmentApi) Get(c *frame.Context) {
  50. param := c.Param("id")
  51. id, _ := strconv.ParseInt(param, 10, 64)
  52. c.Ok(a.SysAttachmentService.GetSysAttachmentById(id))
  53. }
  54. // DownLoad 下载文件
  55. func (a SysAttachmentApi) DownLoad(c *frame.Context) {
  56. param := c.Param("id")
  57. isZIp := c.Query("isZip")
  58. id, _ := strconv.ParseInt(param, 10, 64)
  59. sysAttachment := a.SysAttachmentService.GetSysAttachmentById(id)
  60. filePath := sysAttachment.Path
  61. if gotool.StrUtils.HasNotEmpty(isZIp) {
  62. if gotool.StrUtils.HasNotEmpty(sysAttachment.ZipPath) {
  63. filePath = sysAttachment.ZipPath
  64. }
  65. }
  66. //打开文件
  67. file, err := os.Open(filePath)
  68. if err != nil {
  69. fmt.Println("打开文件错误", err)
  70. }
  71. defer file.Close()
  72. c.File(filePath)
  73. c.Header("Content-Type", "application/octet-stream")
  74. c.Header("Content-Disposition", "attachment; filename="+sysAttachment.Label+"."+sysAttachment.Ext)
  75. c.Header("Content-Transfer-Encoding", "binary")
  76. c.Header("Cache-Control", "no-cache")
  77. }
  78. // Add 新增附件
  79. func (a SysAttachmentApi) Add(c *frame.Context) {
  80. sysAttachment := &model.SysAttachment{}
  81. c.ValidteError(c.ShouldBind(sysAttachment), sysAttachment)
  82. sysAttachment.CreateTime = time.Now()
  83. sysAttachment.CreateBy = admin.GetUserInfo(c).UserName
  84. a.SysAttachmentService.Insert(sysAttachment)
  85. }
  86. // Upload 附件上传
  87. func (a SysAttachmentApi) Upload(c *frame.Context) {
  88. path := config.GetFilePath()
  89. file, header, err := c.Request.FormFile("file")
  90. //fileType := c.Request.FormValue("fileType")
  91. name := c.Request.FormValue("fileName")
  92. ext := ""
  93. if gotool.StrUtils.HasNotEmpty(name) {
  94. ary := strings.Split(name, ".")
  95. ext = ary[1]
  96. }
  97. ary := strings.Split(header.Filename, ".")
  98. if len(ary) > 1 {
  99. ext = ary[1]
  100. }
  101. fileName := gotool.IdUtils.IdUUIDToRan(true) + "." + ext
  102. filePath := path.Path + fileName
  103. compressPath := path.Path + "zip/" + fileName
  104. fileAppend, err := gotool.FileUtils.OpenFileAppend(filePath)
  105. defer fileAppend.Close()
  106. if err != nil {
  107. gotool.Logs.ErrorLog().Println(err)
  108. c.Error()
  109. return
  110. }
  111. _, err = io.Copy(fileAppend, file)
  112. if err != nil {
  113. gotool.Logs.ErrorLog().Println(err)
  114. c.Error()
  115. return
  116. }
  117. zipPath := ""
  118. if strings.Contains(header.Header.Get("Content-Type"), "image") {
  119. zipPath = a.Compress(filePath, compressPath)
  120. }
  121. sysAttachment := model.SysAttachment{}
  122. sysAttachment.Label = strings.Split(header.Filename, ".")[0]
  123. sysAttachment.Type = header.Header.Get("Content-Type")
  124. sysAttachment.Path = filePath
  125. sysAttachment.Ext = ext
  126. sysAttachment.CreateTime = time.Now()
  127. sysAttachment.CreateBy = admin.GetUserInfo(c).UserName
  128. sysAttachment.UpdateTime = time.Now()
  129. sysAttachment.ZipPath = zipPath
  130. sysAttachment.UpdateBy = admin.GetUserInfo(c).UserName
  131. a.SysAttachmentService.Insert(&sysAttachment)
  132. c.Ok(sysAttachment)
  133. }
  134. func (a SysAttachmentApi) Compress(imagePath string, compressPath string) string {
  135. //需要压缩
  136. imgfile, err := os.Open(imagePath)
  137. if err != nil {
  138. log.Println("os.Open::", err)
  139. return ""
  140. }
  141. defer imgfile.Close()
  142. jpgimg, layout, err := image.Decode(imgfile)
  143. if err != nil {
  144. log.Println("jpeg.Decode::", err)
  145. return ""
  146. }
  147. //保存到新文件中
  148. newfile, err := os.Create(compressPath)
  149. if err != nil {
  150. log.Println("Create::", err)
  151. return ""
  152. }
  153. defer newfile.Close()
  154. switch layout {
  155. case "png":
  156. err = png.Encode(newfile, jpgimg)
  157. case "jpeg", "jpg":
  158. err = jpeg.Encode(newfile, jpgimg, &jpeg.Options{Quality: 30})
  159. default:
  160. return ""
  161. }
  162. if err != nil {
  163. log.Println("Encode::", err)
  164. return ""
  165. }
  166. return compressPath
  167. }
  168. // 获取大小的借口
  169. type Sizer interface {
  170. Size() int64
  171. }
  172. // 文件上传接口数据
  173. //
  174. // @Summary 文件上传接口数据
  175. // @Description 文件上传接口数据
  176. // @Tags 文件上传相关接口
  177. // @Accept application/json
  178. // @Produce application/json
  179. // @Param Authorization header string false "Bearer 令牌"
  180. // @Security ApiKeyAuth
  181. // @Success 200 {object} resp.Response{data=string,msg=string} "文件上传结果"
  182. // @Router /sysattachment/qiniuUpload [post]
  183. func (a SysAttachmentApi) QiniuUpload(c *frame.Context) {
  184. file, _, err := c.Request.FormFile("file")
  185. fileSize := file.(Sizer).Size()
  186. var AccessKey = "Rt7_WT03Go8_BwO--ExFlnmsTBk9QUZX_NNnoTMp"
  187. var SerectKey = "NC1_hBQumLFEUCLICzPGPR8xnbn03-Gt5fDV2vlv"
  188. var Bucket = "longping"
  189. putPlicy := storage.PutPolicy{
  190. Scope: Bucket,
  191. }
  192. mac := qbox.NewMac(AccessKey, SerectKey)
  193. upToken := putPlicy.UploadToken(mac)
  194. cfg := storage.Config{
  195. Zone: tool.Zone("longping"),
  196. UseCdnDomains: false,
  197. UseHTTPS: true,
  198. }
  199. putExtra := storage.PutExtra{}
  200. formUploader := storage.NewFormUploader(&cfg)
  201. ret := storage.PutRet{}
  202. err = formUploader.PutWithoutKey(context.Background(), &ret, upToken, file, fileSize, &putExtra)
  203. if err != nil {
  204. c.Error("文件上传错误")
  205. return
  206. }
  207. url := "http://rsbl220vw.hd-bkt.clouddn.com/" + ret.Key
  208. data := response.QiniuResponse{}
  209. data.Url = url
  210. data.Label = ret.Key
  211. c.Ok(data)
  212. }
  213. // Edit 修改附件数据接口
  214. func (a SysAttachmentApi) Edit(c *frame.Context) {
  215. sysAttachment := &model.SysAttachment{}
  216. c.ValidteError(c.ShouldBind(sysAttachment), sysAttachment)
  217. sysAttachment.UpdateTime = time.Now()
  218. sysAttachment.UpdateBy = admin.GetUserInfo(c).UserName
  219. a.SysAttachmentService.Update(sysAttachment)
  220. c.Ok(sysAttachment)
  221. }
  222. // Delete 删除附件数据
  223. func (a SysAttachmentApi) Delete(c *frame.Context) {
  224. //获取sysAttachmentId
  225. param := c.Param("id")
  226. list := make([]int64, 0)
  227. if gotool.StrUtils.HasNotEmpty(param) {
  228. strs := strings.Split(param, ",")
  229. for _, str := range strs {
  230. id, _ := strconv.ParseInt(str, 10, 64)
  231. list = append(list, id)
  232. }
  233. }
  234. //判断是否可以删除
  235. a.SysAttachmentService.Delete(list)
  236. }
  237. // Export 导出excel
  238. func (a SysAttachmentApi) Export(c *frame.Context) {
  239. query := &req.SysAttachmentQuery{}
  240. c.ValidteError(c.ShouldBind(query), query)
  241. list, _ := a.SysAttachmentService.FindList(query)
  242. excelList := make([]interface{}, 0)
  243. for _, sysAttachment := range *list {
  244. excelList = append(excelList, sysAttachment)
  245. }
  246. _, files := excels.ExportExcel(excelList, "附件数据表")
  247. file.DownloadExcel(c, files)
  248. }