9aa751ccf551c2f0000a2e28d97a3e41d46484d9.svn-base 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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/setting"
  12. "github.com/kptyun/KPTCOMM/routers/restful"
  13. "github.com/nfnt/resize"
  14. "image"
  15. "image/gif"
  16. "image/jpeg"
  17. "image/png"
  18. "io"
  19. "mime/multipart"
  20. "net/http"
  21. "os"
  22. "path"
  23. "strconv"
  24. "strings"
  25. )
  26. // 支持的图片后缀名
  27. var supportImageExtNames = []string{".jpg", ".jpeg", ".png", ".ico", ".svg", ".bmp", ".gif"}
  28. /**
  29. check a file is a image or not
  30. */
  31. func isImage(extName string) bool {
  32. for i := 0; i < len(supportImageExtNames); i++ {
  33. if supportImageExtNames[i] == extName {
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. /**
  40. Handler the parse error
  41. */
  42. func parseFormFail(context *gin.Context) {
  43. context.JSON(http.StatusBadRequest, gin.H{
  44. "message": "Can not parse form",
  45. })
  46. }
  47. /**
  48. Upload file handler
  49. */
  50. func UploadFile(context *gin.Context) {
  51. var (
  52. isSupportFile bool
  53. maxUploadSize = setting.AppSetting.FileMaxSize // 最大上传大小
  54. allowTypes = setting.AppSetting.FileAllowType // 可上传的文件类型
  55. distPath string // 最终的输出目录
  56. err error
  57. file *multipart.FileHeader
  58. src multipart.File
  59. dist *os.File
  60. )
  61. // Source
  62. if file, err = context.FormFile("file"); err != nil {
  63. parseFormFail(context)
  64. return
  65. }
  66. sqlname := context.GetHeader("optname")
  67. extname := path.Ext(file.Filename)
  68. if len(allowTypes) != 0 {
  69. for i := 0; i < len(allowTypes); i++ {
  70. if allowTypes[i] == extname {
  71. isSupportFile = true
  72. break
  73. }
  74. }
  75. if isSupportFile == false {
  76. context.JSON(http.StatusBadRequest, gin.H{
  77. "message": "不支持的文件类型: " + extname,
  78. })
  79. return
  80. }
  81. }
  82. if file.Size > int64(maxUploadSize) {
  83. context.JSON(http.StatusBadRequest, gin.H{
  84. "message": "上传文件太大, 最大限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  85. })
  86. return
  87. }
  88. if src, err = file.Open(); err != nil {
  89. // open the file fail...
  90. }
  91. defer src.Close()
  92. hash := md5.New()
  93. io.Copy(hash, src)
  94. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  95. fileName := md5string + extname
  96. // Destination
  97. distPath = setting.CurrentPath + setting.AppSetting.FileSavePath +"/"+ fileName
  98. if dist, err = os.Create(distPath); err != nil {
  99. // create dist file fail...
  100. }
  101. defer dist.Close()
  102. // FIXME: open 2 times
  103. if src, err = file.Open(); err != nil {
  104. //
  105. }
  106. // Copy
  107. io.Copy(dist, src)
  108. var execresult interface{}
  109. params := context.Request.Form
  110. if sqlname != "" {
  111. sql, p := restful.GetSqlByNameDB(sqlname)
  112. if sql != ""{
  113. s_params := make([]interface{}, 0)
  114. paramslist := strings.Split(p,",")
  115. if len(paramslist)>0 && p!="" {
  116. for _, value := range paramslist {
  117. if (strings.ToLower(strings.Trim(value," "))=="jwt_username"){
  118. tempv := params.Get("jwt_username")
  119. s_params = append(s_params, tempv)
  120. }else if (strings.ToLower(strings.Trim(value," "))=="filename"){
  121. s_params = append(s_params, file.Filename)
  122. }else if (strings.ToLower(strings.Trim(value," "))=="newfilename"){
  123. s_params = append(s_params, fileName)
  124. }else{
  125. s_params = append(s_params, params.Get(strings.Trim(value," ")))
  126. }
  127. }
  128. }
  129. execresult, err = execDataBySql(sql, s_params)
  130. }
  131. }
  132. context.JSON(http.StatusOK, gin.H{
  133. "hash": md5string,
  134. "filename": fileName,
  135. "origin": file.Filename,
  136. "size": file.Size,
  137. "execresult": execresult,
  138. })
  139. }
  140. /**
  141. Upload image handler
  142. */
  143. func UploaderImage(context *gin.Context) {
  144. var (
  145. maxUploadSize = setting.AppSetting.ImageMaxSize // 最大上传大小
  146. distPath string // 最终的输出目录
  147. err error
  148. file *multipart.FileHeader
  149. src multipart.File
  150. dist *os.File
  151. )
  152. // Source
  153. if file, err = context.FormFile("file"); err != nil {
  154. parseFormFail(context)
  155. return
  156. }
  157. sqlname := context.GetHeader("optname")
  158. extname := strings.ToLower(path.Ext(file.Filename))
  159. if isImage(extname) == false {
  160. context.JSON(http.StatusBadRequest, gin.H{
  161. "message": "不支持的上传文件类型: " + extname,
  162. })
  163. return
  164. }
  165. if file.Size > int64(maxUploadSize) {
  166. context.JSON(http.StatusBadRequest, gin.H{
  167. "message": "上传文件太大, 最大文件大小限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  168. })
  169. return
  170. }
  171. if src, err = file.Open(); err != nil {
  172. }
  173. defer src.Close()
  174. hash := md5.New()
  175. io.Copy(hash, src)
  176. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  177. fileName := md5string + extname
  178. // Destination
  179. distPath = path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, fileName)
  180. if dist, err = os.Create(distPath); err != nil {
  181. }
  182. defer dist.Close()
  183. // FIXME: open 2 times
  184. if src, err = file.Open(); err != nil {
  185. //
  186. }
  187. // Copy
  188. io.Copy(dist, src)
  189. // 压缩缩略图
  190. // 不管成功与否,都会进行下一步的返回
  191. if _, err := thumbnailify(distPath); err != nil {
  192. }
  193. var execresult interface{}
  194. params := context.Request.Form
  195. if sqlname != "" {
  196. sql, p := restful.GetSqlByNameDB(sqlname)
  197. if sql != ""{
  198. s_params := make([]interface{}, 0)
  199. paramslist := strings.Split(p,",")
  200. if len(paramslist)>0 && p!="" {
  201. for _, value := range paramslist {
  202. if (strings.ToLower(strings.Trim(value," "))=="jwt_username"){
  203. tempv := params.Get("jwt_username")
  204. s_params = append(s_params, tempv)
  205. }else if (strings.ToLower(strings.Trim(value," "))=="filename"){
  206. s_params = append(s_params, file.Filename)
  207. }else if (strings.ToLower(strings.Trim(value," "))=="newfilename"){
  208. s_params = append(s_params, fileName)
  209. }else{
  210. s_params = append(s_params, params.Get(strings.Trim(value," ")))
  211. }
  212. }
  213. }
  214. execresult, err = execDataBySql(sql, s_params)
  215. }
  216. }
  217. context.JSON(http.StatusOK, gin.H{
  218. "hash": md5string,
  219. "filename": fileName,
  220. "origin": file.Filename,
  221. "size": file.Size,
  222. "execresult": execresult,
  223. })
  224. }
  225. /**
  226. Get file raw
  227. */
  228. func GetFileRaw(context *gin.Context) {
  229. filename := context.Param("filename")
  230. filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  231. if isExistFile := fs.PathExists(filePath); isExistFile == false {
  232. // if the path not found
  233. http.NotFound(context.Writer, context.Request)
  234. return
  235. }
  236. http.ServeFile(context.Writer, context.Request, filePath)
  237. }
  238. /**
  239. Download a file
  240. */
  241. func DownloadFile(context *gin.Context) {
  242. filename := context.Param("filename")
  243. filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  244. if isExistFile := fs.PathExists(filePath); isExistFile == false {
  245. // if the path not found
  246. http.NotFound(context.Writer, context.Request)
  247. return
  248. }
  249. http.ServeFile(context.Writer, context.Request, filePath)
  250. }
  251. /**
  252. Get Origin image
  253. */
  254. func GetOriginImage(context *gin.Context) {
  255. filename := context.Param("filename")
  256. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
  257. if fs.PathExists(originImagePath) == false {
  258. // if the path not found
  259. http.NotFound(context.Writer, context.Request)
  260. return
  261. }
  262. http.ServeFile(context.Writer, context.Request, originImagePath)
  263. }
  264. /**
  265. Get thumbnail image
  266. */
  267. func GetThumbnailImage(context *gin.Context) {
  268. filename := context.Param("filename")
  269. thumbnailImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, filename)
  270. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
  271. if fs.PathExists(thumbnailImagePath) == false {
  272. // if thumbnail image not exist, try to get origin image
  273. if fs.PathExists(originImagePath) == true {
  274. http.ServeFile(context.Writer, context.Request, originImagePath)
  275. return
  276. }
  277. // if the path not found
  278. http.NotFound(context.Writer, context.Request)
  279. return
  280. }
  281. http.ServeFile(context.Writer, context.Request, thumbnailImagePath)
  282. }
  283. /**
  284. Generate thumbnail
  285. */
  286. func thumbnailify(imagePath string) (outputPath string, err error) {
  287. var (
  288. file *os.File
  289. img image.Image
  290. )
  291. Filename := strings.ToLower(path.Base(imagePath))
  292. extname := strings.ToLower(path.Ext(imagePath))
  293. outputPath = setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + "/" + Filename
  294. // 读取文件
  295. if file, err = os.Open(imagePath); err != nil {
  296. return
  297. }
  298. defer file.Close()
  299. // decode jpeg into image.Image
  300. switch extname {
  301. case ".jpg", ".jpeg":
  302. img, err = jpeg.Decode(file)
  303. break
  304. case ".png":
  305. img, err = png.Decode(file)
  306. break
  307. case ".gif":
  308. img, err = gif.Decode(file)
  309. break
  310. default:
  311. err = errors.New("Unsupport file type" + extname)
  312. return
  313. }
  314. if img == nil {
  315. err = errors.New("Generate thumbnail fail...")
  316. return
  317. }
  318. m := resize.Thumbnail(uint( setting.AppSetting.ThumbnailMaxWidth), uint(setting.AppSetting.ThumbnailMaxHeight), img, resize.Lanczos3)
  319. out, err := os.Create(outputPath)
  320. if err != nil {
  321. return
  322. }
  323. defer out.Close()
  324. // write new image to file
  325. //decode jpeg/png/gif into image.Image
  326. switch extname {
  327. case ".jpg", ".jpeg":
  328. jpeg.Encode(out, m, nil)
  329. break
  330. case ".png":
  331. png.Encode(out, m)
  332. break
  333. case ".gif":
  334. gif.Encode(out, m, nil)
  335. break
  336. default:
  337. err = errors.New("Unsupport file type" + extname)
  338. return
  339. }
  340. return
  341. }
  342. func UploadFiles(c *gin.Context) {
  343. appG := app.Gin{C: c}
  344. err := c.Request.ParseMultipartForm(200000)
  345. if err != nil {
  346. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  347. return
  348. }
  349. // 获取表单
  350. form := c.Request.MultipartForm
  351. // 获取参数upload后面的多个文件名,存放到数组files里面,
  352. files := form.File["upload"]
  353. // 遍历数组,每取出一个file就拷贝一次
  354. for i, _ := range files {
  355. file, err := files[i].Open()
  356. defer file.Close()
  357. if err != nil {
  358. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  359. return
  360. }
  361. fileName := files[i].Filename
  362. fmt.Println(fileName)
  363. out, err := os.Create(fileName)
  364. defer out.Close()
  365. if err != nil {
  366. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  367. return
  368. }
  369. _, err = io.Copy(out, file)
  370. if err != nil {
  371. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  372. return
  373. }
  374. appG.Response(http.StatusOK, e.SUCCESS, "upload successful \n")
  375. }
  376. }