upload_api.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /*
  2. * @description:
  3. * @Author: CP
  4. * @Date: 2021-03-31 15:06:21
  5. * @FilePath: \design_quantity\web\api\upload_api.go
  6. */
  7. package api
  8. import (
  9. "bytes"
  10. "fmt"
  11. "io"
  12. "log"
  13. "os"
  14. "strings"
  15. "time"
  16. "github.com/kataras/iris/v12"
  17. "go.mod/conf"
  18. "go.mod/services"
  19. "go.mod/web/utils"
  20. "go.mod/web/viewmodels"
  21. )
  22. type UploadApi struct {
  23. //框架-web应用上下文环境
  24. Ctx iris.Context
  25. // // 需要用的service
  26. ServiceContract services.ContractService
  27. ServiceUpload services.UploadService
  28. }
  29. // Upload : 处理文件上传
  30. func (c *UploadApi) Post() {
  31. errCode := 0
  32. id := "0"
  33. defer func() {
  34. if errCode < 0 {
  35. fmt.Println("errCode", errCode)
  36. c.Ctx.JSON(iris.Map{"code": -1, "msg": "上传失败"})
  37. } else {
  38. c.Ctx.JSON(iris.Map{"code": 0, "msg": "上传成功", "data": id})
  39. }
  40. return
  41. }()
  42. file, head, err := c.Ctx.FormFile("file")
  43. if err != nil {
  44. log.Printf("Failed to get form data, err:%s\n", err.Error())
  45. errCode = -1
  46. return
  47. }
  48. defer file.Close()
  49. buf := bytes.NewBuffer(nil)
  50. if _, err := io.Copy(buf, file); err != nil {
  51. log.Printf("Failed to get file data, err:%s\n", err.Error())
  52. errCode = -2
  53. return
  54. }
  55. // 文件元信息-todo
  56. // FileName := head.Filename
  57. FileSize := int64(len(buf.Bytes()))
  58. UploadAt := fmt.Sprintf("%d", time.Now().UnixNano())
  59. Location := conf.MergeLocalRootDir + UploadAt // 存储地址
  60. webLocation := "/public/" + UploadAt + head.Filename
  61. newFile, err := os.Create(Location)
  62. if err != nil {
  63. log.Printf("Failed to create file, err:%s\n", err.Error())
  64. errCode = -3
  65. return
  66. }
  67. defer newFile.Close()
  68. nByte, err := newFile.Write(buf.Bytes())
  69. if int64(nByte) != FileSize || err != nil {
  70. log.Printf("Failed to save data into file, writtenSize:%d, err:%s\n", nByte, err.Error())
  71. errCode = -4
  72. return
  73. }
  74. // fmt.Println(c.Ctx.FormValue("id"))
  75. // treeVM := &viewmodels.TreeSectionContract{}
  76. // err = c.Ctx.ReadForm(treeVM)
  77. // if err != nil {
  78. // log.Println("folder-ValidRule-ReadForm转换异常, error=", err)
  79. // errCode = -6
  80. // return
  81. // }
  82. // fmt.Println(treeVM)
  83. // id, err := utils.GetDecryptId(treeVM.Id)
  84. // if err != nil {
  85. // errCode = -6
  86. // return
  87. // }
  88. ext := strings.Join(head.Header["Content-Type"], "")
  89. id, err = c.ServiceContract.SaveUpload(webLocation, head.Filename, ext)
  90. if err != nil {
  91. errCode = -6
  92. return
  93. }
  94. }
  95. func (c *UploadApi) GetFile() {
  96. fileData := viewmodels.Upload{}
  97. err := c.Ctx.ReadForm(&fileData)
  98. if err != nil {
  99. c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
  100. return
  101. }
  102. id, err := utils.GetDecryptId(fileData.Id)
  103. if err != nil {
  104. c.Ctx.JSON(iris.Map{"code": -1, "msg": "解析异常,请检查参数"})
  105. return
  106. }
  107. fileVM, err := c.ServiceUpload.Get(id)
  108. if err != nil {
  109. c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
  110. return
  111. }
  112. // c.Ctx.Header("Content-Type", "text/html; charset=utf-8;")
  113. // c.Ctx.Header("Content-Disposition", "inline;"+fileVM.Name)
  114. filepath := conf.NormalFileStorage + fileVM.Path
  115. file, err := os.Open(filepath)
  116. readseek := io.ReadSeeker(file)
  117. if err != nil {
  118. c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
  119. return
  120. }
  121. // 读取文件缓冲区
  122. // var buf [128]byte
  123. // // 文件内容字节数组
  124. // var content []byte
  125. // for {
  126. // n, err := file.Read(buf[:])
  127. // if err == io.EOF {
  128. // // 文件读取完成
  129. // break
  130. // }
  131. // if err != nil {
  132. // c.Ctx.JSON(iris.Map{"code": -1, "msg": fmt.Sprintf("%s", err)})
  133. // return
  134. // }
  135. // content = append(content, buf[:n]...)
  136. // }
  137. // c.Ctx.Header("Content-Disposition", "inline;filename="+fileVM.Name+";")
  138. c.Ctx.ServeContent(readseek, fileVM.Name, time.Now())
  139. // c.Ctx.Header("Content-Type", "text/html; charset=utf-8;")
  140. // p, e := c.Ctx.Write(content)
  141. // fmt.Println("p", p)
  142. // fmt.Println("e", e)
  143. }