upload.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. package api
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "image"
  8. "image/gif"
  9. "image/jpeg"
  10. "image/png"
  11. "io"
  12. "io/ioutil"
  13. "mime/multipart"
  14. "net/http"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "../../pkg/app"
  21. "../../pkg/e"
  22. "../../pkg/logging"
  23. "../../pkg/setting"
  24. "../../routers/restful"
  25. "github.com/Anderson-Lu/gofasion/gofasion"
  26. "github.com/astaxie/beego/logs"
  27. "github.com/axetroy/go-fs"
  28. "github.com/gin-gonic/gin"
  29. "github.com/nfnt/resize"
  30. )
  31. // 支持的图片后缀名
  32. var supportImageExtNames = []string{".jpg", ".jpeg", ".png", ".ico", ".svg", ".bmp", ".gif"}
  33. /**
  34. check a file is a image or not
  35. */
  36. func isImage(extName string) bool {
  37. for i := 0; i < len(supportImageExtNames); i++ {
  38. if supportImageExtNames[i] == extName {
  39. return true
  40. }
  41. }
  42. return false
  43. }
  44. /**
  45. Handler the parse error
  46. */
  47. func parseFormFail(context *gin.Context) {
  48. context.JSON(http.StatusBadRequest, gin.H{
  49. "message": "Can not parse form",
  50. })
  51. }
  52. /**
  53. Upload file handler
  54. */
  55. func UploadFile(context *gin.Context) {
  56. appG := app.Gin{C: context}
  57. dictId := context.Param("id")
  58. dictName := context.Param("name")
  59. logging.Info("UploadFile ", context.Keys, dictId, dictName)
  60. var (
  61. isSupportFile bool
  62. maxUploadSize = setting.AppSetting.FileMaxSize // 最大上传大小
  63. allowTypes = setting.AppSetting.FileAllowType // 可上传的文件类型
  64. distPath string // 最终的输出目录
  65. err error
  66. file *multipart.FileHeader
  67. src multipart.File
  68. dist *os.File
  69. )
  70. // Source
  71. if file, err = context.FormFile("file"); err != nil {
  72. parseFormFail(context)
  73. return
  74. }
  75. sqlname := context.GetHeader("optname")
  76. extname := path.Ext(file.Filename)
  77. if len(allowTypes) != 0 {
  78. for i := 0; i < len(allowTypes); i++ {
  79. if allowTypes[i] == extname {
  80. isSupportFile = true
  81. break
  82. }
  83. }
  84. if isSupportFile == false {
  85. context.JSON(http.StatusBadRequest, gin.H{
  86. "message": "不支持的文件类型: " + extname,
  87. })
  88. return
  89. }
  90. }
  91. if file.Size > int64(maxUploadSize) {
  92. context.JSON(http.StatusBadRequest, gin.H{
  93. "message": "上传文件太大, 最大限制为" + strconv.Itoa(int(maxUploadSize)/1048576) + "(M): ",
  94. })
  95. return
  96. }
  97. if src, err = file.Open(); err != nil {
  98. // open the file fail...
  99. }
  100. defer src.Close()
  101. hash := md5.New()
  102. io.Copy(hash, src)
  103. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  104. fileName := md5string + extname
  105. // Destination
  106. filePath := setting.CurrentPath + setting.AppSetting.FileSavePath + dictName + "/"
  107. err = PathCheck(filePath) //检查路径并创建
  108. if err != nil {
  109. fmt.Println("PathCheck err", err)
  110. }
  111. distPath = path.Join(filePath, fileName)
  112. if dist, err = os.Create(distPath); err != nil {
  113. fmt.Println("Create err", err)
  114. }
  115. defer dist.Close()
  116. //distPath = setting.CurrentPath + setting.AppSetting.FileSavePath +"/"+ fileName
  117. if dist, err = os.Create(distPath); err != nil {
  118. // create dist file fail...
  119. }
  120. defer dist.Close()
  121. // FIXME: open 2 times
  122. if src, err = file.Open(); err != nil {
  123. //
  124. }
  125. // Copy
  126. io.Copy(dist, src)
  127. var execresult interface{}
  128. params := context.Request.Form
  129. if sqlname != "" {
  130. sql, p := restful.GetSqlByNameDB(sqlname) //todo insertcustomdoc
  131. if sql != "" {
  132. s_params := make([]interface{}, 0)
  133. paramslist := strings.Split(p, ",")
  134. if len(paramslist) > 0 && p != "" {
  135. for _, value := range paramslist {
  136. fmt.Println("s_params value", s_params, value)
  137. if strings.ToLower(strings.Trim(value, " ")) == "username" { //picpath, picname, username, newpicname
  138. tempv := params.Get("jwt_username")
  139. s_params = append(s_params, tempv)
  140. } else if strings.ToLower(strings.Trim(value, " ")) == "docname" {
  141. s_params = append(s_params, file.Filename)
  142. } else if strings.ToLower(strings.Trim(value, " ")) == "newdocname" {
  143. s_params = append(s_params, fileName)
  144. } else if strings.ToLower(strings.Trim(value, " ")) == "docpath" {
  145. s_params = append(s_params, dictName) //
  146. } else if strings.ToLower(strings.Trim(value, " ")) == "dictid" {
  147. s_params = append(s_params, dictId) //
  148. fmt.Println("s_params", s_params, dictId)
  149. } else if strings.ToLower(strings.Trim(value, " ")) == "filesize" {
  150. s_params = append(s_params, file.Size) //
  151. } else {
  152. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  153. }
  154. }
  155. }
  156. execresult, err = execDataBySql(sql, s_params)
  157. if err != nil {
  158. fmt.Println("execDataBySql err", err)
  159. appG.Response(http.StatusOK, e.ERROR, err.Error())
  160. }
  161. }
  162. }
  163. context.JSON(http.StatusOK, gin.H{
  164. "hash": md5string,
  165. "filename": fileName,
  166. "origin": file.Filename,
  167. "size": file.Size,
  168. "execresult": execresult,
  169. })
  170. }
  171. /**
  172. Upload image handler
  173. */
  174. func UploaderImage(context *gin.Context) {
  175. logging.Info("UploaderImage ", context.Keys)
  176. var (
  177. maxUploadSize = setting.AppSetting.ImageMaxSize // 最大上传大小
  178. distPath string // 最终的输出目录
  179. err error
  180. file *multipart.FileHeader
  181. src multipart.File
  182. dist *os.File
  183. )
  184. // Source
  185. if file, err = context.FormFile("file"); err != nil {
  186. parseFormFail(context)
  187. return
  188. }
  189. sqlname := context.GetHeader("optname")
  190. extname := strings.ToLower(path.Ext(file.Filename))
  191. if isImage(extname) == false {
  192. context.JSON(http.StatusBadRequest, gin.H{
  193. "message": "不支持的上传文件类型: " + extname,
  194. })
  195. return
  196. }
  197. if file.Size > int64(maxUploadSize) {
  198. context.JSON(http.StatusBadRequest, gin.H{
  199. "message": "上传文件太大, 最大文件大小限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  200. })
  201. return
  202. }
  203. if src, err = file.Open(); err != nil {
  204. }
  205. defer src.Close()
  206. hash := md5.New()
  207. io.Copy(hash, src)
  208. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  209. fileName := md5string + extname
  210. //savePathDir := setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName+"/"
  211. //_,err = os.Stat(savePathDir)
  212. //if err == nil {
  213. // fmt.Println(err)//todo 错误处理
  214. //}
  215. //if os.IsNotExist(err) {
  216. // err:=os.Mkdir(setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName,os.ModePerm)
  217. // if err!=nil{
  218. // fmt.Println(err)
  219. // }//目录不存在则创建
  220. //}
  221. // Destination
  222. picPath := setting.CurrentPath + setting.AppSetting.ImageSavePath + sqlname + "/"
  223. err = PathCheck(picPath) //检查路径并创建
  224. if err != nil {
  225. fmt.Println("PathCheck err", err)
  226. }
  227. distPath = path.Join(picPath, fileName)
  228. if dist, err = os.Create(distPath); err != nil {
  229. fmt.Println("Create err", err)
  230. }
  231. defer dist.Close()
  232. // FIXME: open 2 times
  233. if src, err = file.Open(); err != nil {
  234. //
  235. }
  236. defer src.Close()
  237. // Copy
  238. io.Copy(dist, src)
  239. // 压缩缩略图
  240. // 不管成功与否,都会进行下一步的返回
  241. if _, err := thumbnailify(distPath, sqlname); err != nil {
  242. logging.Error("thumbnailify_err", err)
  243. picThumbnailPath := setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + sqlname + "/"
  244. println(picThumbnailPath)
  245. err = PathCheck(picThumbnailPath) //检查路径并创建
  246. distThumbnailPath := path.Join(picThumbnailPath, fileName)
  247. println(distThumbnailPath)
  248. distThumbnail, err := os.Create(distThumbnailPath)
  249. if err != nil {
  250. fmt.Println("CreateThumbnail err", err)
  251. }
  252. srcThumbnail, err := file.Open()
  253. if err != nil {
  254. //
  255. }
  256. io.Copy(distThumbnail, srcThumbnail)
  257. distThumbnail.Close()
  258. src.Close()
  259. }
  260. var execresult interface{}
  261. params := context.Request.Form
  262. if sqlname != "" {
  263. sql, p := restful.GetSqlByNameDB(sqlname)
  264. if sql != "" {
  265. s_params := make([]interface{}, 0)
  266. paramslist := strings.Split(p, ",")
  267. if len(paramslist) > 0 && p != "" {
  268. for _, value := range paramslist {
  269. if strings.ToLower(strings.Trim(value, " ")) == "username" { //picpath, picname, username, newpicname
  270. tempv := params.Get("jwt_username")
  271. s_params = append(s_params, tempv)
  272. } else if strings.ToLower(strings.Trim(value, " ")) == "picname" {
  273. s_params = append(s_params, file.Filename)
  274. } else if strings.ToLower(strings.Trim(value, " ")) == "newpicname" {
  275. s_params = append(s_params, fileName)
  276. } else if strings.ToLower(strings.Trim(value, " ")) == "picpath" {
  277. s_params = append(s_params, sqlname) //全路径加文件名
  278. } else {
  279. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  280. }
  281. }
  282. }
  283. execresult, err = execDataBySql(sql, s_params)
  284. if err != nil {
  285. fmt.Println("execDataBySql err", err)
  286. }
  287. }
  288. }
  289. context.JSON(http.StatusOK, gin.H{
  290. "hash": md5string,
  291. "filename": fileName,
  292. "origin": file.Filename,
  293. "size": file.Size,
  294. "execresult": execresult,
  295. })
  296. }
  297. /**
  298. Get file raw
  299. */
  300. func GetFileRaw(context *gin.Context) {
  301. filename := context.Param("filename")
  302. logging.Info("GetFileRaw ", context.Keys, filename)
  303. filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  304. if isExistFile := fs.PathExists(filePath); isExistFile == false {
  305. // if the path not found
  306. http.NotFound(context.Writer, context.Request)
  307. return
  308. }
  309. http.ServeFile(context.Writer, context.Request, filePath)
  310. }
  311. /**
  312. Download a file
  313. */
  314. func DownloadFile(context *gin.Context) {
  315. filename := context.Param("filename")
  316. logging.Info("DownloadFile ", context.Keys, filename)
  317. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", filename).QueryString()
  318. if eqpic == nil {
  319. http.NotFound(context.Writer, context.Request)
  320. return
  321. }
  322. originFilePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqpic[0]["docpath"], eqpic[0]["newdocname"])
  323. if fs.PathExists(originFilePath) == false {
  324. // if the path not found
  325. http.NotFound(context.Writer, context.Request)
  326. return
  327. }
  328. http.ServeFile(context.Writer, context.Request, originFilePath)
  329. }
  330. /**
  331. Get Origin image
  332. */
  333. func GetOriginImage(context *gin.Context) {
  334. //appG := app.Gin{C: context}
  335. filename := context.Param("filename")
  336. logging.Info("GetOriginImage ", context.Keys, filename)
  337. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  338. if eqpic == nil {
  339. http.NotFound(context.Writer, context.Request)
  340. return
  341. }
  342. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, eqpic[0]["picpath"], eqpic[0]["newpicname"])
  343. if fs.PathExists(originImagePath) == false {
  344. // if the path not found
  345. http.NotFound(context.Writer, context.Request)
  346. return
  347. }
  348. http.ServeFile(context.Writer, context.Request, originImagePath)
  349. //appG.Response(http.StatusOK, e.SUCCESS, eqpic[0]["picname"])
  350. }
  351. /**
  352. Get thumbnail image
  353. */
  354. func GetThumbnailImage(context *gin.Context) {
  355. filename := context.Param("filename")
  356. logging.Info("GetThumbnailImage ", context.Keys, filename)
  357. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  358. if eqpic == nil {
  359. http.NotFound(context.Writer, context.Request)
  360. return
  361. }
  362. thumbnailImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, eqpic[0]["picpath"], eqpic[0]["newpicname"])
  363. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
  364. if fs.PathExists(thumbnailImagePath) == false {
  365. // if thumbnail image not exist, try to get origin image
  366. if fs.PathExists(originImagePath) == true {
  367. http.ServeFile(context.Writer, context.Request, originImagePath)
  368. return
  369. }
  370. // if the path not found
  371. http.NotFound(context.Writer, context.Request)
  372. return
  373. }
  374. http.ServeFile(context.Writer, context.Request, thumbnailImagePath)
  375. }
  376. /**
  377. Generate thumbnail
  378. */
  379. func thumbnailify(imagePath, subdirectory string) (outputPath string, err error) {
  380. var (
  381. file *os.File
  382. img image.Image
  383. )
  384. Filename := strings.ToLower(path.Base(imagePath))
  385. extname := strings.ToLower(path.Ext(imagePath))
  386. outputPath = setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory + "/" + Filename
  387. err = PathCheck(setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory)
  388. if err != nil {
  389. fmt.Println("thumbnailify PathCheck err", err)
  390. }
  391. // 读取文件
  392. if file, err = os.Open(imagePath); err != nil {
  393. return
  394. }
  395. defer file.Close()
  396. // decode jpeg into image.Image
  397. switch extname {
  398. case ".jpg", ".jpeg":
  399. img, err = jpeg.Decode(file)
  400. break
  401. case ".png":
  402. img, err = png.Decode(file)
  403. break
  404. case ".gif":
  405. img, err = gif.Decode(file)
  406. break
  407. default:
  408. err = errors.New("Unsupport file type" + extname)
  409. return
  410. }
  411. if img == nil {
  412. err = errors.New("Generate thumbnail fail...")
  413. return
  414. }
  415. m := resize.Thumbnail(uint(setting.AppSetting.ThumbnailMaxWidth), uint(setting.AppSetting.ThumbnailMaxHeight), img, resize.Lanczos3)
  416. out, err := os.Create(outputPath)
  417. if err != nil {
  418. return
  419. }
  420. defer out.Close()
  421. // write new image to file
  422. //decode jpeg/png/gif into image.Image
  423. switch extname {
  424. case ".jpg", ".jpeg":
  425. jpeg.Encode(out, m, nil)
  426. break
  427. case ".png":
  428. png.Encode(out, m)
  429. break
  430. case ".gif":
  431. gif.Encode(out, m, nil)
  432. break
  433. default:
  434. err = errors.New("Unsupport file type" + extname)
  435. return
  436. }
  437. return
  438. }
  439. func UploadFiles(c *gin.Context) {
  440. logging.Info("UploadFiles ", c.Keys)
  441. appG := app.Gin{C: c}
  442. err := c.Request.ParseMultipartForm(200000)
  443. if err != nil {
  444. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  445. return
  446. }
  447. // 获取表单
  448. form := c.Request.MultipartForm
  449. // 获取参数upload后面的多个文件名,存放到数组files里面,
  450. files := form.File["upload"]
  451. // 遍历数组,每取出一个file就拷贝一次
  452. for i, _ := range files {
  453. file, err := files[i].Open()
  454. defer file.Close()
  455. if err != nil {
  456. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  457. return
  458. }
  459. fileName := files[i].Filename
  460. fmt.Println(fileName)
  461. out, err := os.Create(fileName)
  462. defer out.Close()
  463. if err != nil {
  464. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  465. return
  466. }
  467. _, err = io.Copy(out, file)
  468. if err != nil {
  469. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  470. return
  471. }
  472. appG.Response(http.StatusOK, e.SUCCESS, "upload successful \n")
  473. }
  474. }
  475. func PathCheck(path string) (err error) {
  476. b, err := PathExists(path)
  477. if err != nil {
  478. fmt.Println("exist err", err)
  479. }
  480. if !b {
  481. fmt.Println(path, " 目录不存在,重新创建")
  482. err = os.Mkdir(path, 0777)
  483. if err != nil {
  484. fmt.Println("Mkdir err", err)
  485. }
  486. }
  487. return
  488. }
  489. func PathExists(path string) (bool, error) {
  490. _, err := os.Stat(path)
  491. if err == nil {
  492. return true, nil
  493. }
  494. if os.IsNotExist(err) {
  495. return false, nil
  496. }
  497. return false, err
  498. }
  499. func UploadFileCRM(c *gin.Context) {
  500. appG := app.Gin{C: c}
  501. file, err := appG.C.FormFile("file")
  502. if err != nil {
  503. logs.Error(err)
  504. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  505. return
  506. }
  507. tx := restful.Engine.NewSession()
  508. defer tx.Close()
  509. basePath := "./"
  510. filename := basePath + filepath.Base(file.Filename)
  511. if err := appG.C.SaveUploadedFile(file, filename); err != nil {
  512. logs.Error(err)
  513. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  514. return
  515. }
  516. queryData, err := tx.SQL(` insert into file(filename,path,uploaddate)values(?,?,now()) ON DUPLICATE KEY UPDATE filename = ? ,path = ?,uploaddate = now() `, file.Filename, filename, file.Filename, filename).Execute()
  517. if err != nil {
  518. logs.Error(err)
  519. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  520. return
  521. } else {
  522. data := make(map[string]interface{})
  523. LastInsertId, _ := queryData.LastInsertId()
  524. data["LastInsertId"] = LastInsertId
  525. appG.Response(http.StatusOK, e.SUCCESS, data)
  526. }
  527. //c.String(http.StatusOK, fmt.Sprintf("文件 %s 上传成功 ", file.Filename))
  528. }
  529. func DownloadFileCRM(c *gin.Context) {
  530. appG := app.Gin{C: c}
  531. dataByte, _ := ioutil.ReadAll(c.Request.Body)
  532. parammaps := gofasion.NewFasion(string(dataByte))
  533. fileId := parammaps.Get("fileId").ValueStr()
  534. tx := restful.Engine.NewSession()
  535. defer tx.Close()
  536. fileInfoList, err := tx.SQL(` select path from file where id = ? `, fileId).Query().List()
  537. if err != nil {
  538. logs.Error(err)
  539. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  540. return
  541. }
  542. filepath := ""
  543. for _, fileinfo := range fileInfoList {
  544. filepath = fileinfo["path"].(string)
  545. }
  546. c.File(filepath)
  547. }