SysAttachmentController.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package partial
  2. import (
  3. "crypto/sha1"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "github.com/pkg/errors"
  7. "io"
  8. "io/ioutil"
  9. "mime"
  10. "mime/multipart"
  11. "os"
  12. "path"
  13. "strconv"
  14. "time"
  15. "git.qianqiusoft.com/qianqiusoft/light-apiengine/entitys"
  16. syslogs "git.qianqiusoft.com/qianqiusoft/light-apiengine/logs"
  17. sysmodel "git.qianqiusoft.com/qianqiusoft/light-apiengine/models"
  18. sysutils "git.qianqiusoft.com/qianqiusoft/light-apiengine/utils"
  19. )
  20. /**
  21. * 附件上传/下载接口
  22. */
  23. type AttachementUpDownloader interface {
  24. /**
  25. * @brief: 附件上传接口
  26. * @param1 file: post 多媒体file
  27. * @param2 fileHeader: 文件相关头部信息
  28. * @return1: 附件信息,主要包括id,url, hash和大小。其他字段会自动设置
  29. * @return4: 错误信息
  30. */
  31. Upload(multipart.File, *multipart.FileHeader)(*sysmodel.SysAttachment, error)
  32. /**
  33. * @brief: 附件下载
  34. * @param1 ctx: 上下文
  35. * @param2 attach: 福建对象
  36. */
  37. Download(*entitys.CtrlContext, *sysmodel.SysAttachment)
  38. }
  39. // 附件上传下载接口
  40. var _attachementUpDownloader AttachementUpDownloader = &defaultAttachUpDownloader{}
  41. /**
  42. * @brief: 设置附件上传下载接口
  43. * @param1 uder: 上传下载接口
  44. */
  45. func SetAttachementUpDownloader(uder AttachementUpDownloader){
  46. if uder != nil{
  47. _attachementUpDownloader = uder
  48. }
  49. }
  50. // _Upload
  51. // @Title _Upload
  52. // @Description 上传文件
  53. // @Success 200 {object} Account
  54. // @Failure 403 :id is empty
  55. func SysAttachment_Upload(c *entitys.CtrlContext) {
  56. attach, err := doUpload2(c)
  57. if err == nil {
  58. c.Ctx.JSON(200, sysmodel.SysReturn{200, "", attach.Id})
  59. syslogs.Debug("上传附件成功:", attach.Name, attach.Size)
  60. } else {
  61. c.Ctx.JSON(500, sysmodel.SysReturn{500, err.Error(), nil})
  62. }
  63. }
  64. // _Download
  65. // @Title _Download
  66. // @Description 下载文件
  67. // @Param id string false "文件ID"
  68. // @Success 200 {object} Account
  69. // @Failure 403 :id is empty
  70. func SysAttachment_Download(c *entitys.CtrlContext) {
  71. attachId := c.Ctx.Query("id")
  72. var engine = c.PlatformDbEngine
  73. var attach sysmodel.SysAttachment
  74. has, err := engine.ID(attachId).Get(&attach)
  75. if err != nil || !has {
  76. syslogs.Error("获取附件出错了:", err)
  77. c.Ctx.JSON(500, sysmodel.SysReturn{500, "获取附件出错了", nil})
  78. return
  79. }
  80. if _attachementUpDownloader != nil{
  81. _attachementUpDownloader.Download(c, &attach)
  82. }else{
  83. c.Ctx.JSON(500, gin.H{"code": 500, "msg": "附件上传下载接口为nil", "data": nil})
  84. }
  85. }
  86. // _Delete
  87. // @Title _Delete
  88. // @Description 删除文件
  89. // @Param id string false "文件ID"
  90. // @Success 200 {object} Account
  91. // @Failure 403 :id is empty
  92. func SysAttachment_Delete(c *entitys.CtrlContext) {
  93. attrId := c.Ctx.Query("id")
  94. attach := &sysmodel.SysAttachment{}
  95. attach.Id = attrId
  96. _, err := c.PlatformDbEngine.ID(attrId).Delete(attach)
  97. if err != nil {
  98. syslogs.Error("删除附件出错了:", err)
  99. c.Ctx.JSON(500, sysmodel.SysReturn{500, err.Error(), nil})
  100. return
  101. }
  102. syslogs.Debug("删除附件:", attrId)
  103. c.Ctx.JSON(200, sysmodel.SysReturn{200, "", attrId})
  104. }
  105. // _Get
  106. // @Title _Get
  107. // @Description 获取附件信息
  108. // @Param id string false "附件id"
  109. // @Success 200 {object} Account
  110. // @Failure 403 :id is empty
  111. func SysAttachment_Get(c *entitys.CtrlContext) {
  112. var id = c.Ctx.Query("id")
  113. var attach sysmodel.SysAttachment
  114. has, err := c.PlatformDbEngine.ID(id).Get(&attach)
  115. if err == nil {
  116. if has {
  117. c.Ctx.JSON(200, sysmodel.SysReturn{200, "", attach})
  118. } else {
  119. c.Ctx.JSON(200, sysmodel.SysReturn{500, "附件不存在", nil})
  120. }
  121. } else {
  122. c.Ctx.JSON(200, sysmodel.SysReturn{500, err.Error(), nil})
  123. }
  124. }
  125. func doUpload(c *entitys.CtrlContext) (*sysmodel.SysAttachment, error) {
  126. file, fInfo, err := c.Ctx.Request.FormFile("file")
  127. if err != nil {
  128. syslogs.Error("上传出错了:", err)
  129. return nil, err
  130. }
  131. download, hash, length, err := sysutils.PostFile(file)
  132. if err != nil {
  133. return nil, err
  134. }
  135. userId := c.Ctx.GetString("user_id")
  136. attach := &sysmodel.SysAttachment{}
  137. attach.Id = sysutils.NewUUID()
  138. attach.Name = fInfo.Filename
  139. attach.Size = length
  140. attach.Url = download
  141. attach.CreateBy = userId
  142. attach.CreateTime = time.Now()
  143. attach.Ext = path.Ext(attach.Name)
  144. attach.Hash = hash
  145. _, err = c.Db.InsertOne(attach)
  146. if err != nil {
  147. syslogs.Error("保存附件出错了:", err)
  148. return nil, err
  149. }
  150. return attach, nil
  151. }
  152. func doUpload2(c *entitys.CtrlContext) (*sysmodel.SysAttachment, error) {
  153. file, fInfo, err := c.Ctx.Request.FormFile("file")
  154. if err != nil {
  155. syslogs.Error("上传出错了:", err)
  156. return nil, err
  157. }
  158. defer file.Close()
  159. var attach *sysmodel.SysAttachment = nil
  160. if _attachementUpDownloader != nil{
  161. attach, err = _attachementUpDownloader.Upload(file, fInfo)
  162. if err !=nil{
  163. return nil, err
  164. }
  165. }else{
  166. return nil, errors.New("附件上传下载接口为nil")
  167. }
  168. userId := c.Ctx.GetString("user_id")
  169. if attach.Id == ""{
  170. attach.Id = sysutils.NewUUID()
  171. }
  172. if attach.Size <= 0{
  173. attach.Size = int32((fInfo.Size))
  174. }
  175. attach.Name = fInfo.Filename
  176. attach.CreateBy = userId
  177. attach.CreateTime = time.Now()
  178. attach.Ext = path.Ext(attach.Name)
  179. _, err = c.PlatformDbEngine.InsertOne(attach)
  180. if err != nil {
  181. syslogs.Error("保存附件出错了:", err)
  182. return nil, err
  183. }
  184. return attach, nil
  185. }
  186. func mkdir(dir string) error {
  187. _, err := os.Stat(dir)
  188. if err != nil {
  189. err = os.MkdirAll(dir, os.ModePerm)
  190. }
  191. return err
  192. }
  193. func FileHasH(filePath string) string {
  194. bytes, err := ioutil.ReadFile(filePath)
  195. if err == nil && len(bytes) > 0 {
  196. return fmt.Sprintf("%x", sha1.Sum(bytes))
  197. }
  198. return ""
  199. }
  200. /**
  201. * @brief: 默认
  202. */
  203. type defaultAttachUpDownloader struct{
  204. }
  205. /**
  206. * @brief: 附件上传接口
  207. * @param1 file: post 多媒体file
  208. * @param1 header: 文件相头信息
  209. * @return1: 附件信息,主要包括id,url, hash和大小。其他字段会自动设置
  210. * @return2: 错误信息
  211. */
  212. func(d *defaultAttachUpDownloader)Upload(file multipart.File, header *multipart.FileHeader)(*sysmodel.SysAttachment, error){
  213. fileDir := fmt.Sprintf("files/")
  214. if err := mkdir(fileDir); err != nil {
  215. syslogs.Info("文件夹创建失败")
  216. return nil, err
  217. }
  218. attachId := sysutils.NewUUID()
  219. filePath := fileDir + attachId
  220. fW, err := os.Create(filePath)
  221. if err != nil {
  222. syslogs.Info("文件创建失败")
  223. return nil, err
  224. }
  225. defer fW.Close()
  226. length, err := io.Copy(fW, file)
  227. if err != nil {
  228. syslogs.Info("文件保存失败")
  229. return nil, err
  230. }
  231. attach := &sysmodel.SysAttachment{}
  232. attach.Id = attachId
  233. attach.Url = "/api/v1/sys_attachment/download?id=" + attach.Id
  234. attach.Hash = ""
  235. attach.Size = int32(length)
  236. return attach, nil
  237. }
  238. /**
  239. * @brief: 附件下载
  240. * @param1 ctx: 上下文
  241. * @param2 id: 附件记录的id
  242. */
  243. func(d *defaultAttachUpDownloader)Download(c *entitys.CtrlContext, attach *sysmodel.SysAttachment){
  244. filePath := "files/" + attach.Id
  245. c.Ctx.Writer.Header().Add("Content-Disposition", "attachment;filename=\""+sysutils.FormatForBrowse(c.Ctx.Request.UserAgent(), attach.Name)+"\"")
  246. c.Ctx.Writer.Header().Add("Content-Type", mime.TypeByExtension(attach.Ext))
  247. c.Ctx.Writer.Header().Add("Content-Length", strconv.FormatInt(int64(attach.Size), 10))
  248. c.Ctx.Writer.Header().Add("Accept-Ranges", "bytes")
  249. if !sysutils.Exists(filePath) {
  250. c.Ctx.Writer.WriteHeader(400)
  251. return
  252. }
  253. fmt.Println("---->", c.Ctx.Writer.Header().Get("Content-Disposition"))
  254. fmt.Println("---->", c.Ctx.Writer.Header().Get("Content-Type"))
  255. fmt.Println("---->", c.Ctx.Writer.Header().Get("Content-Length"))
  256. fmt.Println("---->", c.Ctx.Writer.Header().Get("Accept-Ranges"))
  257. c.Ctx.File(filePath)
  258. }
  259. func __none_func_sys_attachment__(params ...interface{}) bool {
  260. return true
  261. }