84bc15f09e7842b0e6ab6f90193d8226dca6e192.svn-base 14 KB

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