53b246452c9c902dade40aa0eb85ad428c5fac5e.svn-base 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. "github.com/kptyun/KPTCOMM/pkg/app"
  10. "github.com/kptyun/KPTCOMM/pkg/e"
  11. "github.com/kptyun/KPTCOMM/pkg/logging"
  12. "github.com/kptyun/KPTCOMM/pkg/setting"
  13. "github.com/kptyun/KPTCOMM/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. // Copy
  233. io.Copy(dist, src)
  234. // 压缩缩略图
  235. // 不管成功与否,都会进行下一步的返回
  236. if _, err := thumbnailify(distPath,sqlname); err != nil {
  237. }
  238. var execresult interface{}
  239. params := context.Request.Form
  240. if sqlname != "" {
  241. sql, p := restful.GetSqlByNameDB(sqlname)
  242. if sql != ""{
  243. s_params := make([]interface{}, 0)
  244. paramslist := strings.Split(p,",")
  245. if len(paramslist)>0 && p!="" {
  246. for _, value := range paramslist {
  247. if (strings.ToLower(strings.Trim(value," "))=="username"){//picpath, picname, username, newpicname
  248. tempv := params.Get("jwt_username")
  249. s_params = append(s_params, tempv)
  250. }else if (strings.ToLower(strings.Trim(value," "))=="picname"){
  251. s_params = append(s_params, file.Filename)
  252. }else if (strings.ToLower(strings.Trim(value," "))=="newpicname"){
  253. s_params = append(s_params, fileName)
  254. }else if (strings.ToLower(strings.Trim(value," "))=="picpath"){
  255. s_params = append(s_params, sqlname) //全路径加文件名
  256. } else{
  257. s_params = append(s_params, params.Get(strings.Trim(value," ")))
  258. }
  259. }
  260. }
  261. execresult, err = execDataBySql(sql, s_params)
  262. if err != nil{
  263. fmt.Println("execDataBySql err",err)
  264. }
  265. }
  266. }
  267. context.JSON(http.StatusOK, gin.H{
  268. "hash": md5string,
  269. "filename": fileName,
  270. "origin": file.Filename,
  271. "size": file.Size,
  272. "execresult": execresult,
  273. })
  274. }
  275. /**
  276. Get file raw
  277. */
  278. func GetFileRaw(context *gin.Context) {
  279. filename := context.Param("filename")
  280. logging.Info("GetFileRaw ",context.Keys,filename)
  281. filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  282. if isExistFile := fs.PathExists(filePath); isExistFile == false {
  283. // if the path not found
  284. http.NotFound(context.Writer, context.Request)
  285. return
  286. }
  287. http.ServeFile(context.Writer, context.Request, filePath)
  288. }
  289. /**
  290. Download a file
  291. */
  292. func DownloadFile(context *gin.Context) {
  293. filename := context.Param("filename")
  294. logging.Info("DownloadFile ",context.Keys,filename)
  295. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", filename).QueryString()
  296. if eqpic == nil {
  297. http.NotFound(context.Writer, context.Request)
  298. return
  299. }
  300. originFilePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath,eqpic[0]["docpath"],eqpic[0]["newdocname"])
  301. if fs.PathExists(originFilePath) == false {
  302. // if the path not found
  303. http.NotFound(context.Writer, context.Request)
  304. return
  305. }
  306. http.ServeFile(context.Writer, context.Request, originFilePath)
  307. }
  308. /**
  309. Get Origin image
  310. */
  311. func GetOriginImage(context *gin.Context) {
  312. //appG := app.Gin{C: context}
  313. filename := context.Param("filename")
  314. logging.Info("GetOriginImage ",context.Keys,filename)
  315. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  316. if eqpic == nil {
  317. http.NotFound(context.Writer, context.Request)
  318. return
  319. }
  320. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath,eqpic[0]["picpath"],eqpic[0]["newpicname"])
  321. if fs.PathExists(originImagePath) == false {
  322. // if the path not found
  323. http.NotFound(context.Writer, context.Request)
  324. return
  325. }
  326. http.ServeFile(context.Writer, context.Request, originImagePath)
  327. //appG.Response(http.StatusOK, e.SUCCESS, eqpic[0]["picname"])
  328. }
  329. /**
  330. Get thumbnail image
  331. */
  332. func GetThumbnailImage(context *gin.Context) {
  333. filename := context.Param("filename")
  334. logging.Info("GetThumbnailImage ",context.Keys,filename)
  335. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  336. if eqpic == nil {
  337. http.NotFound(context.Writer, context.Request)
  338. return
  339. }
  340. thumbnailImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath,eqpic[0]["picpath"],eqpic[0]["newpicname"])
  341. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
  342. if fs.PathExists(thumbnailImagePath) == false {
  343. // if thumbnail image not exist, try to get origin image
  344. if fs.PathExists(originImagePath) == true {
  345. http.ServeFile(context.Writer, context.Request, originImagePath)
  346. return
  347. }
  348. // if the path not found
  349. http.NotFound(context.Writer, context.Request)
  350. return
  351. }
  352. http.ServeFile(context.Writer, context.Request, thumbnailImagePath)
  353. }
  354. /**
  355. Generate thumbnail
  356. */
  357. func thumbnailify(imagePath,subdirectory string) (outputPath string, err error) {
  358. var (
  359. file *os.File
  360. img image.Image
  361. )
  362. Filename := strings.ToLower(path.Base(imagePath))
  363. extname := strings.ToLower(path.Ext(imagePath))
  364. outputPath = setting.CurrentPath + setting.AppSetting.ThumbnailSavePath +subdirectory+ "/" + Filename
  365. err = PathCheck(setting.CurrentPath + setting.AppSetting.ThumbnailSavePath +subdirectory)
  366. if err !=nil{
  367. fmt.Println("thumbnailify PathCheck err",err)
  368. }
  369. // 读取文件
  370. if file, err = os.Open(imagePath); err != nil {
  371. return
  372. }
  373. defer file.Close()
  374. // decode jpeg into image.Image
  375. switch extname {
  376. case ".jpg", ".jpeg":
  377. img, err = jpeg.Decode(file)
  378. break
  379. case ".png":
  380. img, err = png.Decode(file)
  381. break
  382. case ".gif":
  383. img, err = gif.Decode(file)
  384. break
  385. default:
  386. err = errors.New("Unsupport file type" + extname)
  387. return
  388. }
  389. if img == nil {
  390. err = errors.New("Generate thumbnail fail...")
  391. return
  392. }
  393. m := resize.Thumbnail(uint( setting.AppSetting.ThumbnailMaxWidth), uint(setting.AppSetting.ThumbnailMaxHeight), img, resize.Lanczos3)
  394. out, err := os.Create(outputPath)
  395. if err != nil {
  396. return
  397. }
  398. defer out.Close()
  399. // write new image to file
  400. //decode jpeg/png/gif into image.Image
  401. switch extname {
  402. case ".jpg", ".jpeg":
  403. jpeg.Encode(out, m, nil)
  404. break
  405. case ".png":
  406. png.Encode(out, m)
  407. break
  408. case ".gif":
  409. gif.Encode(out, m, nil)
  410. break
  411. default:
  412. err = errors.New("Unsupport file type" + extname)
  413. return
  414. }
  415. return
  416. }
  417. func UploadFiles(c *gin.Context) {
  418. logging.Info("UploadFiles ",c.Keys)
  419. appG := app.Gin{C: c}
  420. err := c.Request.ParseMultipartForm(200000)
  421. if err != nil {
  422. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  423. return
  424. }
  425. // 获取表单
  426. form := c.Request.MultipartForm
  427. // 获取参数upload后面的多个文件名,存放到数组files里面,
  428. files := form.File["upload"]
  429. // 遍历数组,每取出一个file就拷贝一次
  430. for i, _ := range files {
  431. file, err := files[i].Open()
  432. defer file.Close()
  433. if err != nil {
  434. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  435. return
  436. }
  437. fileName := files[i].Filename
  438. fmt.Println(fileName)
  439. out, err := os.Create(fileName)
  440. defer out.Close()
  441. if err != nil {
  442. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  443. return
  444. }
  445. _, err = io.Copy(out, file)
  446. if err != nil {
  447. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  448. return
  449. }
  450. appG.Response(http.StatusOK, e.SUCCESS, "upload successful \n")
  451. }
  452. }
  453. func PathCheck(path string)(err error){
  454. b,err :=PathExists(path)
  455. if err != nil {
  456. fmt.Println("exist err",err)
  457. }
  458. if !b{
  459. fmt.Println(path," 目录不存在,重新创建")
  460. err = os.Mkdir(path, 0777)
  461. if err != nil {
  462. fmt.Println("Mkdir err",err)
  463. }
  464. }
  465. return
  466. }
  467. func PathExists(path string) (bool, error) {
  468. _, err := os.Stat(path)
  469. if err == nil {
  470. return true, nil
  471. }
  472. if os.IsNotExist(err) {
  473. return false, nil
  474. }
  475. return false, err
  476. }