upload.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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. "mime/multipart"
  13. "net/http"
  14. "os"
  15. "path"
  16. "strconv"
  17. "strings"
  18. "../../pkg/app"
  19. "../../pkg/e"
  20. "../../pkg/logging"
  21. "../../pkg/setting"
  22. "../../routers/restful"
  23. "github.com/astaxie/beego/logs"
  24. "github.com/axetroy/go-fs"
  25. "github.com/gin-gonic/gin"
  26. "github.com/nfnt/resize"
  27. "github.com/tealeg/xlsx"
  28. )
  29. // 支持的图片后缀名
  30. var supportImageExtNames = []string{".jpg", ".jpeg", ".png", ".ico", ".svg", ".bmp", ".gif"}
  31. /**
  32. check a file is a image or not
  33. */
  34. func isImage(extName string) bool {
  35. for i := 0; i < len(supportImageExtNames); i++ {
  36. if supportImageExtNames[i] == extName {
  37. return true
  38. }
  39. }
  40. return false
  41. }
  42. /**
  43. Handler the parse error
  44. */
  45. func parseFormFail(context *gin.Context) {
  46. context.JSON(http.StatusBadRequest, gin.H{
  47. "msg": "fail",
  48. "message": "Can not parse form",
  49. })
  50. }
  51. /**
  52. Upload file handler
  53. */
  54. func UploadFile(context *gin.Context) {
  55. appG := app.Gin{C: context}
  56. dictId := context.Param("id")
  57. dictName := context.Param("name")
  58. logging.Info("UploadFile ", context.Keys, dictId, dictName)
  59. var (
  60. isSupportFile bool
  61. maxUploadSize = setting.AppSetting.FileMaxSize // 最大上传大小
  62. allowTypes = setting.AppSetting.FileAllowType // 可上传的文件类型
  63. distPath string // 最终的输出目录
  64. err error
  65. file *multipart.FileHeader
  66. src multipart.File
  67. dist *os.File
  68. )
  69. // Source
  70. if file, err = context.FormFile("file"); err != nil {
  71. parseFormFail(context)
  72. return
  73. }
  74. sqlname := context.GetHeader("optname")
  75. extname := path.Ext(file.Filename)
  76. if len(allowTypes) != 0 {
  77. for i := 0; i < len(allowTypes); i++ {
  78. if allowTypes[i] == extname {
  79. isSupportFile = true
  80. break
  81. }
  82. }
  83. if isSupportFile == false {
  84. context.JSON(http.StatusBadRequest, gin.H{
  85. "message": "不支持的文件类型: " + extname,
  86. })
  87. return
  88. }
  89. }
  90. if file.Size > int64(maxUploadSize) {
  91. context.JSON(http.StatusBadRequest, gin.H{
  92. "message": "上传文件太大, 最大限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  93. })
  94. return
  95. }
  96. if src, err = file.Open(); err != nil {
  97. // open the file fail...
  98. }
  99. defer src.Close()
  100. hash := md5.New()
  101. io.Copy(hash, src)
  102. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  103. fileName := md5string + extname
  104. // Destination
  105. filePath := setting.CurrentPath + setting.AppSetting.FileSavePath + dictName + "/"
  106. err = PathCheck(filePath) //检查路径并创建
  107. if err != nil {
  108. fmt.Println("PathCheck err", err)
  109. }
  110. distPath = path.Join(filePath, fileName)
  111. if dist, err = os.Create(distPath); err != nil {
  112. fmt.Println("Create err", err)
  113. }
  114. defer dist.Close()
  115. //distPath = setting.CurrentPath + setting.AppSetting.FileSavePath +"/"+ fileName
  116. if dist, err = os.Create(distPath); err != nil {
  117. // create dist file fail...
  118. }
  119. defer dist.Close()
  120. // FIXME: open 2 times
  121. if src, err = file.Open(); err != nil {
  122. //
  123. }
  124. // Copy
  125. io.Copy(dist, src)
  126. var execresult interface{}
  127. params := context.Request.Form
  128. if sqlname != "" {
  129. sql, p := restful.GetSqlByNameDB(sqlname) //todo insertcustomdoc
  130. if sql != "" {
  131. s_params := make([]interface{}, 0)
  132. paramslist := strings.Split(p, ",")
  133. if len(paramslist) > 0 && p != "" {
  134. for _, value := range paramslist {
  135. fmt.Println("s_params value", s_params, value)
  136. if strings.ToLower(strings.Trim(value, " ")) == "username" { //picpath, picname, username, newpicname
  137. tempv := params.Get("jwt_username")
  138. s_params = append(s_params, tempv)
  139. } else if strings.ToLower(strings.Trim(value, " ")) == "docname" {
  140. s_params = append(s_params, file.Filename)
  141. } else if strings.ToLower(strings.Trim(value, " ")) == "newdocname" {
  142. s_params = append(s_params, fileName)
  143. } else if strings.ToLower(strings.Trim(value, " ")) == "docpath" {
  144. s_params = append(s_params, dictName) //
  145. } else if strings.ToLower(strings.Trim(value, " ")) == "dictid" {
  146. s_params = append(s_params, dictId) //
  147. fmt.Println("s_params", s_params, dictId)
  148. } else if strings.ToLower(strings.Trim(value, " ")) == "filesize" {
  149. s_params = append(s_params, file.Size) //
  150. } else {
  151. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  152. }
  153. }
  154. }
  155. execresult, err = execDataBySql(sql, s_params)
  156. if err != nil {
  157. fmt.Println("execDataBySql err", err)
  158. appG.Response(http.StatusOK, e.ERROR, err.Error())
  159. }
  160. }
  161. }
  162. context.JSON(http.StatusOK, gin.H{
  163. "hash": md5string,
  164. "filename": fileName,
  165. "origin": file.Filename,
  166. "size": file.Size,
  167. "execresult": execresult,
  168. })
  169. }
  170. /**
  171. Upload image handler
  172. */
  173. func UploaderImage(context *gin.Context) {
  174. logging.Info("UploaderImage ", context.Keys)
  175. var (
  176. maxUploadSize = setting.AppSetting.ImageMaxSize // 最大上传大小
  177. distPath string // 最终的输出目录
  178. err error
  179. file *multipart.FileHeader
  180. src multipart.File
  181. dist *os.File
  182. )
  183. // Source
  184. if file, err = context.FormFile("file"); err != nil {
  185. parseFormFail(context)
  186. return
  187. }
  188. sqlname := context.GetHeader("optname")
  189. extname := strings.ToLower(path.Ext(file.Filename))
  190. if isImage(extname) == false {
  191. context.JSON(http.StatusBadRequest, gin.H{
  192. "message": "不支持的上传文件类型: " + extname,
  193. })
  194. return
  195. }
  196. if file.Size > int64(maxUploadSize) {
  197. context.JSON(http.StatusBadRequest, gin.H{
  198. "message": "上传文件太大, 最大文件大小限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  199. })
  200. return
  201. }
  202. if src, err = file.Open(); err != nil {
  203. }
  204. defer src.Close()
  205. hash := md5.New()
  206. io.Copy(hash, src)
  207. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  208. fileName := md5string + extname
  209. //savePathDir := setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName+"/"
  210. //_,err = os.Stat(savePathDir)
  211. //if err == nil {
  212. // fmt.Println(err)//todo 错误处理
  213. //}
  214. //if os.IsNotExist(err) {
  215. // err:=os.Mkdir(setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName,os.ModePerm)
  216. // if err!=nil{
  217. // fmt.Println(err)
  218. // }//目录不存在则创建
  219. //}
  220. // Destination
  221. picPath := setting.CurrentPath + setting.AppSetting.ImageSavePath + sqlname + "/"
  222. err = PathCheck(picPath) //检查路径并创建
  223. if err != nil {
  224. fmt.Println("PathCheck err", err)
  225. }
  226. distPath = path.Join(picPath, fileName)
  227. if dist, err = os.Create(distPath); err != nil {
  228. fmt.Println("Create err", err)
  229. }
  230. defer dist.Close()
  231. // FIXME: open 2 times
  232. if src, err = file.Open(); err != nil {
  233. //
  234. }
  235. defer src.Close()
  236. // Copy
  237. io.Copy(dist, src)
  238. // 压缩缩略图
  239. // 不管成功与否,都会进行下一步的返回
  240. if _, err := thumbnailify(distPath, sqlname); err != nil {
  241. logging.Error("thumbnailify_err", err)
  242. picThumbnailPath := setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + sqlname + "/"
  243. println(picThumbnailPath)
  244. err = PathCheck(picThumbnailPath) //检查路径并创建
  245. distThumbnailPath := path.Join(picThumbnailPath, fileName)
  246. println(distThumbnailPath)
  247. distThumbnail, err := os.Create(distThumbnailPath)
  248. if err != nil {
  249. fmt.Println("CreateThumbnail err", err)
  250. }
  251. srcThumbnail, err := file.Open()
  252. if err != nil {
  253. //
  254. }
  255. io.Copy(distThumbnail, srcThumbnail)
  256. distThumbnail.Close()
  257. src.Close()
  258. }
  259. var execresult interface{}
  260. params := context.Request.Form
  261. if sqlname != "" {
  262. sql, p := restful.GetSqlByNameDB(sqlname)
  263. if sql != "" {
  264. s_params := make([]interface{}, 0)
  265. paramslist := strings.Split(p, ",")
  266. if len(paramslist) > 0 && p != "" {
  267. for _, value := range paramslist {
  268. if strings.ToLower(strings.Trim(value, " ")) == "username" { //picpath, picname, username, newpicname
  269. tempv := params.Get("jwt_username")
  270. s_params = append(s_params, tempv)
  271. } else if strings.ToLower(strings.Trim(value, " ")) == "picname" {
  272. s_params = append(s_params, file.Filename)
  273. } else if strings.ToLower(strings.Trim(value, " ")) == "newpicname" {
  274. s_params = append(s_params, fileName)
  275. } else if strings.ToLower(strings.Trim(value, " ")) == "picpath" {
  276. s_params = append(s_params, sqlname) //全路径加文件名
  277. } else {
  278. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  279. }
  280. }
  281. }
  282. execresult, err = execDataBySql(sql, s_params)
  283. if err != nil {
  284. fmt.Println("execDataBySql err", err)
  285. }
  286. }
  287. }
  288. context.JSON(http.StatusOK, gin.H{
  289. "hash": md5string,
  290. "filename": fileName,
  291. "origin": file.Filename,
  292. "size": file.Size,
  293. "execresult": execresult,
  294. })
  295. }
  296. /**
  297. Upload image handler
  298. */
  299. func UploaderTmrImage(context *gin.Context) {
  300. logging.Info("UploaderTmrImage ", context.Keys)
  301. var (
  302. maxUploadSize = setting.AppSetting.ImageMaxSize // 最大上传大小
  303. distPath string // 最终的输出目录
  304. err error
  305. file *multipart.FileHeader
  306. src multipart.File
  307. dist *os.File
  308. )
  309. // Source
  310. if file, err = context.FormFile("file"); err != nil {
  311. parseFormFail(context)
  312. return
  313. }
  314. pastureid := context.GetHeader("pastureid") //牧场id
  315. projuctid := context.GetHeader("projuctid") // 主计划id
  316. pfid := context.GetHeader("pfid") // 配方id
  317. optid := context.GetHeader("optid") //子计划id
  318. catchtime := context.GetHeader("catchtime") // 捕获时间
  319. picclass := context.GetHeader("picclass") // 图片分类
  320. extname := strings.ToLower(path.Ext(file.Filename))
  321. if isImage(extname) == false {
  322. context.JSON(http.StatusBadRequest, gin.H{
  323. "msg": "fail",
  324. "message": "不支持的上传文件类型: " + extname,
  325. })
  326. return
  327. }
  328. if file.Size > int64(maxUploadSize) {
  329. context.JSON(http.StatusBadRequest, gin.H{
  330. "msg": "fail",
  331. "message": "上传文件太大, 最大文件大小限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  332. })
  333. return
  334. }
  335. if src, err = file.Open(); err != nil {
  336. }
  337. defer src.Close()
  338. hash := md5.New()
  339. io.Copy(hash, src)
  340. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  341. fileName := md5string + extname
  342. //savePathDir := setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName+"/"
  343. //_,err = os.Stat(savePathDir)
  344. //if err == nil {
  345. // fmt.Println(err)//todo 错误处理
  346. //}
  347. //if os.IsNotExist(err) {
  348. // err:=os.Mkdir(setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName,os.ModePerm)
  349. // if err!=nil{
  350. // fmt.Println(err)
  351. // }//目录不存在则创建
  352. //}
  353. // Destination
  354. picPath := setting.CurrentPath + setting.AppSetting.ImageSavePath + projuctid + "/"
  355. err = PathCheck(picPath) //检查路径并创建
  356. if err != nil {
  357. fmt.Println("PathCheck err", err)
  358. }
  359. distPath = path.Join(picPath, fileName)
  360. if dist, err = os.Create(distPath); err != nil {
  361. fmt.Println("Create err", err)
  362. }
  363. defer dist.Close()
  364. // FIXME: open 2 times
  365. if src, err = file.Open(); err != nil {
  366. //
  367. }
  368. defer src.Close()
  369. // Copy
  370. io.Copy(dist, src)
  371. // 压缩缩略图
  372. // 不管成功与否,都会进行下一步的返回
  373. if _, err := thumbnailify(distPath, projuctid); err != nil {
  374. logging.Error("thumbnailify_err", err)
  375. picThumbnailPath := setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + projuctid + "/"
  376. println(picThumbnailPath)
  377. err = PathCheck(picThumbnailPath) //检查路径并创建
  378. distThumbnailPath := path.Join(picThumbnailPath, fileName)
  379. println(distThumbnailPath)
  380. distThumbnail, err := os.Create(distThumbnailPath)
  381. if err != nil {
  382. fmt.Println("CreateThumbnail err", err)
  383. }
  384. srcThumbnail, err := file.Open()
  385. if err != nil {
  386. //
  387. }
  388. io.Copy(distThumbnail, srcThumbnail)
  389. distThumbnail.Close()
  390. src.Close()
  391. }
  392. var execresult interface{}
  393. params := context.Request.Form
  394. sqlname := "insertcustompic"
  395. if sqlname != "" {
  396. sql, p := restful.GetSqlByNameDB(sqlname)
  397. if sql != "" {
  398. s_params := make([]interface{}, 0)
  399. paramslist := strings.Split(p, ",")
  400. if len(paramslist) > 0 && p != "" {
  401. for _, value := range paramslist {
  402. switch strings.ToLower(strings.Trim(value, " ")) {
  403. case "username":
  404. tempv := params.Get("jwt_username")
  405. s_params = append(s_params, tempv)
  406. case "picname":
  407. s_params = append(s_params, file.Filename)
  408. case "newpicname":
  409. s_params = append(s_params, fileName)
  410. case "picpath":
  411. s_params = append(s_params, projuctid)
  412. case "pastureid":
  413. s_params = append(s_params, pastureid)
  414. case "projuctid":
  415. s_params = append(s_params, projuctid)
  416. case "pfid":
  417. s_params = append(s_params, pfid)
  418. case "optid":
  419. s_params = append(s_params, optid)
  420. case "catchtime":
  421. s_params = append(s_params, catchtime)
  422. case "picclass":
  423. s_params = append(s_params, picclass)
  424. default:
  425. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  426. }
  427. }
  428. }
  429. execresult, err = execDataBySql(sql, s_params)
  430. if err != nil {
  431. fmt.Println("execDataBySql err", err)
  432. }
  433. }
  434. }
  435. context.JSON(http.StatusOK, gin.H{
  436. "msg": "ok",
  437. "hash": md5string,
  438. "filename": fileName,
  439. "origin": file.Filename,
  440. "size": file.Size,
  441. "execresult": execresult,
  442. })
  443. }
  444. /**
  445. Get file raw
  446. */
  447. func GetFileRaw(context *gin.Context) {
  448. filename := context.Param("filename")
  449. logging.Info("GetFileRaw ", context.Keys, filename)
  450. filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  451. if isExistFile := fs.PathExists(filePath); isExistFile == false {
  452. // if the path not found
  453. http.NotFound(context.Writer, context.Request)
  454. return
  455. }
  456. http.ServeFile(context.Writer, context.Request, filePath)
  457. }
  458. /**
  459. Download a file
  460. */
  461. func DownloadFile(context *gin.Context) {
  462. filename := context.Param("filename")
  463. logging.Info("DownloadFile ", context.Keys, filename)
  464. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", filename).QueryString()
  465. if eqpic == nil {
  466. http.NotFound(context.Writer, context.Request)
  467. return
  468. }
  469. originFilePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqpic[0]["docpath"], eqpic[0]["newdocname"])
  470. if fs.PathExists(originFilePath) == false {
  471. // if the path not found
  472. http.NotFound(context.Writer, context.Request)
  473. return
  474. }
  475. http.ServeFile(context.Writer, context.Request, originFilePath)
  476. }
  477. /**
  478. Get Origin image
  479. */
  480. func GetOriginImage(context *gin.Context) {
  481. //appG := app.Gin{C: context}
  482. filename := context.Param("filename")
  483. logging.Info("GetOriginImage ", context.Keys, filename)
  484. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  485. if eqpic == nil {
  486. http.NotFound(context.Writer, context.Request)
  487. return
  488. }
  489. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, eqpic[0]["picpath"], eqpic[0]["newpicname"])
  490. if fs.PathExists(originImagePath) == false {
  491. // if the path not found
  492. http.NotFound(context.Writer, context.Request)
  493. return
  494. }
  495. http.ServeFile(context.Writer, context.Request, originImagePath)
  496. //appG.Response(http.StatusOK, e.SUCCESS, eqpic[0]["picname"])
  497. }
  498. /**
  499. Get thumbnail image
  500. */
  501. func GetThumbnailImage(context *gin.Context) {
  502. filename := context.Param("filename")
  503. logging.Info("GetThumbnailImage ", context.Keys, filename)
  504. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  505. if eqpic == nil {
  506. http.NotFound(context.Writer, context.Request)
  507. return
  508. }
  509. thumbnailImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, eqpic[0]["picpath"], eqpic[0]["newpicname"])
  510. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
  511. if fs.PathExists(thumbnailImagePath) == false {
  512. // if thumbnail image not exist, try to get origin image
  513. if fs.PathExists(originImagePath) == true {
  514. http.ServeFile(context.Writer, context.Request, originImagePath)
  515. return
  516. }
  517. // if the path not found
  518. http.NotFound(context.Writer, context.Request)
  519. return
  520. }
  521. http.ServeFile(context.Writer, context.Request, thumbnailImagePath)
  522. }
  523. /**
  524. Generate thumbnail
  525. */
  526. func thumbnailify(imagePath, subdirectory string) (outputPath string, err error) {
  527. var (
  528. file *os.File
  529. img image.Image
  530. )
  531. Filename := strings.ToLower(path.Base(imagePath))
  532. extname := strings.ToLower(path.Ext(imagePath))
  533. outputPath = setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory + "/" + Filename
  534. err = PathCheck(setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory)
  535. if err != nil {
  536. fmt.Println("thumbnailify PathCheck err", err)
  537. }
  538. // 读取文件
  539. if file, err = os.Open(imagePath); err != nil {
  540. return
  541. }
  542. defer file.Close()
  543. // decode jpeg into image.Image
  544. switch extname {
  545. case ".jpg", ".jpeg":
  546. img, err = jpeg.Decode(file)
  547. break
  548. case ".png":
  549. img, err = png.Decode(file)
  550. break
  551. case ".gif":
  552. img, err = gif.Decode(file)
  553. break
  554. default:
  555. err = errors.New("Unsupport file type" + extname)
  556. return
  557. }
  558. if img == nil {
  559. err = errors.New("Generate thumbnail fail...")
  560. return
  561. }
  562. m := resize.Thumbnail(uint(setting.AppSetting.ThumbnailMaxWidth), uint(setting.AppSetting.ThumbnailMaxHeight), img, resize.Lanczos3)
  563. out, err := os.Create(outputPath)
  564. if err != nil {
  565. return
  566. }
  567. defer out.Close()
  568. // write new image to file
  569. //decode jpeg/png/gif into image.Image
  570. switch extname {
  571. case ".jpg", ".jpeg":
  572. jpeg.Encode(out, m, nil)
  573. break
  574. case ".png":
  575. png.Encode(out, m)
  576. break
  577. case ".gif":
  578. gif.Encode(out, m, nil)
  579. break
  580. default:
  581. err = errors.New("Unsupport file type" + extname)
  582. return
  583. }
  584. return
  585. }
  586. func UploadFiles(c *gin.Context) {
  587. logging.Info("UploadFiles ", c.Keys)
  588. appG := app.Gin{C: c}
  589. err := c.Request.ParseMultipartForm(200000)
  590. if err != nil {
  591. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  592. return
  593. }
  594. // 获取表单
  595. form := c.Request.MultipartForm
  596. // 获取参数upload后面的多个文件名,存放到数组files里面,
  597. files := form.File["upload"]
  598. // 遍历数组,每取出一个file就拷贝一次
  599. for i, _ := range files {
  600. file, err := files[i].Open()
  601. defer file.Close()
  602. if err != nil {
  603. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  604. return
  605. }
  606. fileName := files[i].Filename
  607. fmt.Println(fileName)
  608. out, err := os.Create(fileName)
  609. defer out.Close()
  610. if err != nil {
  611. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  612. return
  613. }
  614. _, err = io.Copy(out, file)
  615. if err != nil {
  616. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  617. return
  618. }
  619. appG.Response(http.StatusOK, e.SUCCESS, "upload successful \n")
  620. }
  621. }
  622. func PathCheck(path string) (err error) {
  623. b, err := PathExists(path)
  624. if err != nil {
  625. fmt.Println("exist err", err)
  626. }
  627. if !b {
  628. fmt.Println(path, " 目录不存在,重新创建")
  629. err = os.Mkdir(path, 0777)
  630. if err != nil {
  631. fmt.Println("Mkdir err", err)
  632. }
  633. }
  634. return
  635. }
  636. func PathExists(path string) (bool, error) {
  637. _, err := os.Stat(path)
  638. if err == nil {
  639. return true, nil
  640. }
  641. if os.IsNotExist(err) {
  642. return false, nil
  643. }
  644. return false, err
  645. }
  646. func GetBarfeedremainExcel(c *gin.Context) {
  647. var file *xlsx.File
  648. var sheet *xlsx.Sheet
  649. var row *xlsx.Row
  650. var cell *xlsx.Cell
  651. style := xlsx.NewStyle()
  652. style.ApplyBorder = true
  653. border := *xlsx.NewBorder("thin", "thin", "thin", "thin")
  654. style.Border = border
  655. style.Font.Size = 11
  656. style.Alignment = xlsx.Alignment{
  657. Horizontal: "center",
  658. Vertical: "center",
  659. WrapText: true,
  660. // ShrinkToFit: true,
  661. }
  662. style.ApplyBorder = true
  663. file = xlsx.NewFile()
  664. sheet, _ = file.AddSheet("Sheet1")
  665. // row = sheet.AddRow()
  666. // cell = row.AddCell()
  667. row = sheet.AddRow()
  668. cell = row.AddCell()
  669. cell.Value = "栏舍名称"
  670. // cell.Merge(0, 1)
  671. cell.SetStyle(style)
  672. cell = row.AddCell()
  673. cell.SetValue("剩料量(kg)")
  674. cell.SetStyle(style)
  675. cell = row.AddCell()
  676. cell.SetValue("班次(第一班,第二班,第三班)")
  677. cell.SetStyle(style)
  678. cell = row.AddCell()
  679. cell.SetValue("收集时间")
  680. cell.SetStyle(style)
  681. cell = row.AddCell()
  682. cell.SetValue("操作人")
  683. cell.SetStyle(style)
  684. cell = row.AddCell()
  685. tx := restful.Engine.NewSession()
  686. defer tx.Close()
  687. dataList, err := tx.SQL(`select bname from bar where pastureid = (select column_default as pastureid from information_schema.COLUMNS
  688. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid') order by sort ,id`, setting.DatabaseSetting.Name).Query().List()
  689. if err != nil {
  690. logs.Error("CronScheduled-error-1:", err)
  691. return
  692. }
  693. for _, data := range dataList {
  694. row = sheet.AddRow()
  695. cell = row.AddCell()
  696. cell.SetValue(data["bname"])
  697. cell.SetStyle(style)
  698. }
  699. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  700. c.Header("Content-Disposition", "attachment; filename="+"栏舍剩料记录导入模板.xlsx")
  701. c.Header("Content-Transfer-Encoding", "binary")
  702. _ = file.Write(c.Writer)
  703. }