upload.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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. "path/filepath"
  17. "strconv"
  18. "strings"
  19. "../../pkg/app"
  20. "../../pkg/e"
  21. "../../pkg/logging"
  22. "../../pkg/setting"
  23. "../../routers/restful"
  24. "github.com/astaxie/beego/logs"
  25. "github.com/axetroy/go-fs"
  26. "github.com/gin-gonic/gin"
  27. "github.com/nfnt/resize"
  28. "github.com/tealeg/xlsx"
  29. )
  30. // 支持的图片后缀名
  31. var supportImageExtNames = []string{".jpg", ".jpeg", ".png", ".ico", ".svg", ".bmp", ".gif"}
  32. /**
  33. check a file is a image or not
  34. */
  35. func isImage(extName string) bool {
  36. for i := 0; i < len(supportImageExtNames); i++ {
  37. if supportImageExtNames[i] == extName {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. /**
  44. Handler the parse error
  45. */
  46. func parseFormFail(context *gin.Context) {
  47. context.JSON(http.StatusBadRequest, gin.H{
  48. "msg": "fail",
  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": "上传文件太大, 最大限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  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. Upload image handler
  299. */
  300. func UploaderTmrImage(context *gin.Context) {
  301. logging.Info("UploaderTmrImage ", context.Keys)
  302. var (
  303. maxUploadSize = setting.AppSetting.ImageMaxSize // 最大上传大小
  304. distPath string // 最终的输出目录
  305. err error
  306. file *multipart.FileHeader
  307. src multipart.File
  308. dist *os.File
  309. )
  310. // Source
  311. if file, err = context.FormFile("file"); err != nil {
  312. parseFormFail(context)
  313. return
  314. }
  315. pastureid := context.GetHeader("pastureid") //牧场id
  316. projuctid := context.GetHeader("projuctid") // 主计划id
  317. pfid := context.GetHeader("pfid") // 配方id
  318. optid := context.GetHeader("optid") //子计划id
  319. catchtime := context.GetHeader("catchtime") // 捕获时间
  320. picclass := context.GetHeader("picclass") // 图片分类
  321. extname := strings.ToLower(path.Ext(file.Filename))
  322. if isImage(extname) == false {
  323. context.JSON(http.StatusBadRequest, gin.H{
  324. "msg": "fail",
  325. "message": "不支持的上传文件类型: " + extname,
  326. })
  327. return
  328. }
  329. if file.Size > int64(maxUploadSize) {
  330. context.JSON(http.StatusBadRequest, gin.H{
  331. "msg": "fail",
  332. "message": "上传文件太大, 最大文件大小限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
  333. })
  334. return
  335. }
  336. if src, err = file.Open(); err != nil {
  337. }
  338. defer src.Close()
  339. hash := md5.New()
  340. io.Copy(hash, src)
  341. md5string := hex.EncodeToString(hash.Sum([]byte("")))
  342. fileName := md5string + extname
  343. //savePathDir := setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName+"/"
  344. //_,err = os.Stat(savePathDir)
  345. //if err == nil {
  346. // fmt.Println(err)//todo 错误处理
  347. //}
  348. //if os.IsNotExist(err) {
  349. // err:=os.Mkdir(setting.CurrentPath+setting.AppSetting.ImageSavePath+fileName,os.ModePerm)
  350. // if err!=nil{
  351. // fmt.Println(err)
  352. // }//目录不存在则创建
  353. //}
  354. // Destination
  355. picPath := setting.CurrentPath + setting.AppSetting.ImageSavePath + projuctid + "/"
  356. err = PathCheck(picPath) //检查路径并创建
  357. if err != nil {
  358. fmt.Println("PathCheck err", err)
  359. }
  360. distPath = path.Join(picPath, fileName)
  361. if dist, err = os.Create(distPath); err != nil {
  362. fmt.Println("Create err", err)
  363. }
  364. defer dist.Close()
  365. // FIXME: open 2 times
  366. if src, err = file.Open(); err != nil {
  367. //
  368. }
  369. defer src.Close()
  370. // Copy
  371. io.Copy(dist, src)
  372. // 压缩缩略图
  373. // 不管成功与否,都会进行下一步的返回
  374. if _, err := thumbnailify(distPath, projuctid); err != nil {
  375. logging.Error("thumbnailify_err", err)
  376. picThumbnailPath := setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + projuctid + "/"
  377. println(picThumbnailPath)
  378. err = PathCheck(picThumbnailPath) //检查路径并创建
  379. distThumbnailPath := path.Join(picThumbnailPath, fileName)
  380. println(distThumbnailPath)
  381. distThumbnail, err := os.Create(distThumbnailPath)
  382. if err != nil {
  383. fmt.Println("CreateThumbnail err", err)
  384. }
  385. srcThumbnail, err := file.Open()
  386. if err != nil {
  387. //
  388. }
  389. io.Copy(distThumbnail, srcThumbnail)
  390. distThumbnail.Close()
  391. src.Close()
  392. }
  393. var execresult interface{}
  394. params := context.Request.Form
  395. sqlname := "insertcustompic"
  396. if sqlname != "" {
  397. sql, p := restful.GetSqlByNameDB(sqlname)
  398. if sql != "" {
  399. s_params := make([]interface{}, 0)
  400. paramslist := strings.Split(p, ",")
  401. if len(paramslist) > 0 && p != "" {
  402. for _, value := range paramslist {
  403. switch strings.ToLower(strings.Trim(value, " ")) {
  404. case "username":
  405. tempv := params.Get("jwt_username")
  406. s_params = append(s_params, tempv)
  407. case "picname":
  408. s_params = append(s_params, file.Filename)
  409. case "newpicname":
  410. s_params = append(s_params, fileName)
  411. case "picpath":
  412. s_params = append(s_params, projuctid)
  413. case "pastureid":
  414. s_params = append(s_params, pastureid)
  415. case "projuctid":
  416. s_params = append(s_params, projuctid)
  417. case "pfid":
  418. s_params = append(s_params, pfid)
  419. case "optid":
  420. s_params = append(s_params, optid)
  421. case "catchtime":
  422. s_params = append(s_params, catchtime)
  423. case "picclass":
  424. s_params = append(s_params, picclass)
  425. default:
  426. s_params = append(s_params, params.Get(strings.Trim(value, " ")))
  427. }
  428. }
  429. }
  430. execresult, err = execDataBySql(sql, s_params)
  431. if err != nil {
  432. fmt.Println("execDataBySql err", err)
  433. }
  434. }
  435. }
  436. context.JSON(http.StatusOK, gin.H{
  437. "msg": "ok",
  438. "hash": md5string,
  439. "filename": fileName,
  440. "origin": file.Filename,
  441. "size": file.Size,
  442. "execresult": execresult,
  443. })
  444. }
  445. /**
  446. Get file raw
  447. */
  448. func GetFileRaw(context *gin.Context) {
  449. filename := context.Param("filename")
  450. logging.Info("GetFileRaw ", context.Keys, filename)
  451. filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
  452. if isExistFile := fs.PathExists(filePath); isExistFile == false {
  453. // if the path not found
  454. http.NotFound(context.Writer, context.Request)
  455. return
  456. }
  457. http.ServeFile(context.Writer, context.Request, filePath)
  458. }
  459. /**
  460. Download a file
  461. */
  462. func DownloadFile(context *gin.Context) {
  463. filename := context.Param("filename")
  464. logging.Info("DownloadFile ", context.Keys, filename)
  465. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_doc where id = ? ", filename).QueryString()
  466. if eqpic == nil {
  467. http.NotFound(context.Writer, context.Request)
  468. return
  469. }
  470. originFilePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqpic[0]["docpath"], eqpic[0]["newdocname"])
  471. if fs.PathExists(originFilePath) == false {
  472. // if the path not found
  473. http.NotFound(context.Writer, context.Request)
  474. return
  475. }
  476. http.ServeFile(context.Writer, context.Request, originFilePath)
  477. }
  478. /**
  479. Get Origin image
  480. */
  481. func GetOriginImage(context *gin.Context) {
  482. //appG := app.Gin{C: context}
  483. filename := context.Param("filename")
  484. logging.Info("GetOriginImage ", context.Keys, filename)
  485. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  486. if eqpic == nil {
  487. http.NotFound(context.Writer, context.Request)
  488. return
  489. }
  490. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, eqpic[0]["picpath"], eqpic[0]["newpicname"])
  491. if fs.PathExists(originImagePath) == false {
  492. // if the path not found
  493. http.NotFound(context.Writer, context.Request)
  494. return
  495. }
  496. http.ServeFile(context.Writer, context.Request, originImagePath)
  497. //appG.Response(http.StatusOK, e.SUCCESS, eqpic[0]["picname"])
  498. }
  499. /**
  500. Get thumbnail image
  501. */
  502. func GetThumbnailImage(context *gin.Context) {
  503. filename := context.Param("filename")
  504. logging.Info("GetThumbnailImage ", context.Keys, filename)
  505. eqpic, _ := restful.Engine.SQL("SELECT * FROM eq_pic where id = ? ", filename).QueryString()
  506. if eqpic == nil {
  507. http.NotFound(context.Writer, context.Request)
  508. return
  509. }
  510. thumbnailImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, eqpic[0]["picpath"], eqpic[0]["newpicname"])
  511. originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
  512. if fs.PathExists(thumbnailImagePath) == false {
  513. // if thumbnail image not exist, try to get origin image
  514. if fs.PathExists(originImagePath) == true {
  515. http.ServeFile(context.Writer, context.Request, originImagePath)
  516. return
  517. }
  518. // if the path not found
  519. http.NotFound(context.Writer, context.Request)
  520. return
  521. }
  522. http.ServeFile(context.Writer, context.Request, thumbnailImagePath)
  523. }
  524. /**
  525. Generate thumbnail
  526. */
  527. func thumbnailify(imagePath, subdirectory string) (outputPath string, err error) {
  528. var (
  529. file *os.File
  530. img image.Image
  531. )
  532. Filename := strings.ToLower(path.Base(imagePath))
  533. extname := strings.ToLower(path.Ext(imagePath))
  534. outputPath = setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory + "/" + Filename
  535. err = PathCheck(setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory)
  536. if err != nil {
  537. fmt.Println("thumbnailify PathCheck err", err)
  538. }
  539. // 读取文件
  540. if file, err = os.Open(imagePath); err != nil {
  541. return
  542. }
  543. defer file.Close()
  544. // decode jpeg into image.Image
  545. switch extname {
  546. case ".jpg", ".jpeg":
  547. img, err = jpeg.Decode(file)
  548. break
  549. case ".png":
  550. img, err = png.Decode(file)
  551. break
  552. case ".gif":
  553. img, err = gif.Decode(file)
  554. break
  555. default:
  556. err = errors.New("Unsupport file type" + extname)
  557. return
  558. }
  559. if img == nil {
  560. err = errors.New("Generate thumbnail fail...")
  561. return
  562. }
  563. m := resize.Thumbnail(uint(setting.AppSetting.ThumbnailMaxWidth), uint(setting.AppSetting.ThumbnailMaxHeight), img, resize.Lanczos3)
  564. out, err := os.Create(outputPath)
  565. if err != nil {
  566. return
  567. }
  568. defer out.Close()
  569. // write new image to file
  570. //decode jpeg/png/gif into image.Image
  571. switch extname {
  572. case ".jpg", ".jpeg":
  573. jpeg.Encode(out, m, nil)
  574. break
  575. case ".png":
  576. png.Encode(out, m)
  577. break
  578. case ".gif":
  579. gif.Encode(out, m, nil)
  580. break
  581. default:
  582. err = errors.New("Unsupport file type" + extname)
  583. return
  584. }
  585. return
  586. }
  587. func UploadFiles(c *gin.Context) {
  588. logging.Info("UploadFiles ", c.Keys)
  589. appG := app.Gin{C: c}
  590. err := c.Request.ParseMultipartForm(200000)
  591. if err != nil {
  592. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  593. return
  594. }
  595. // 获取表单
  596. form := c.Request.MultipartForm
  597. // 获取参数upload后面的多个文件名,存放到数组files里面,
  598. files := form.File["upload"]
  599. // 遍历数组,每取出一个file就拷贝一次
  600. for i, _ := range files {
  601. file, err := files[i].Open()
  602. defer file.Close()
  603. if err != nil {
  604. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  605. return
  606. }
  607. fileName := files[i].Filename
  608. fmt.Println(fileName)
  609. out, err := os.Create(fileName)
  610. defer out.Close()
  611. if err != nil {
  612. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  613. return
  614. }
  615. _, err = io.Copy(out, file)
  616. if err != nil {
  617. appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
  618. return
  619. }
  620. appG.Response(http.StatusOK, e.SUCCESS, "upload successful \n")
  621. }
  622. }
  623. func PathCheck(path string) (err error) {
  624. b, err := PathExists(path)
  625. if err != nil {
  626. fmt.Println("exist err", err)
  627. }
  628. if !b {
  629. fmt.Println(path, " 目录不存在,重新创建")
  630. err = os.Mkdir(path, 0777)
  631. if err != nil {
  632. fmt.Println("Mkdir err", err)
  633. }
  634. }
  635. return
  636. }
  637. func PathExists(path string) (bool, error) {
  638. _, err := os.Stat(path)
  639. if err == nil {
  640. return true, nil
  641. }
  642. if os.IsNotExist(err) {
  643. return false, nil
  644. }
  645. return false, err
  646. }
  647. func GetBarfeedremainExcel(c *gin.Context) {
  648. var file *xlsx.File
  649. var sheet *xlsx.Sheet
  650. var row *xlsx.Row
  651. var cell *xlsx.Cell
  652. style := xlsx.NewStyle()
  653. style.ApplyBorder = true
  654. border := *xlsx.NewBorder("thin", "thin", "thin", "thin")
  655. style.Border = border
  656. style.Font.Size = 11
  657. style.Alignment = xlsx.Alignment{
  658. Horizontal: "center",
  659. Vertical: "center",
  660. WrapText: true,
  661. // ShrinkToFit: true,
  662. }
  663. style.ApplyBorder = true
  664. file = xlsx.NewFile()
  665. sheet, _ = file.AddSheet("Sheet1")
  666. // row = sheet.AddRow()
  667. // cell = row.AddCell()
  668. row = sheet.AddRow()
  669. cell = row.AddCell()
  670. cell.Value = "栏舍名称"
  671. // cell.Merge(0, 1)
  672. cell.SetStyle(style)
  673. cell = row.AddCell()
  674. cell.SetValue("剩料量(kg)")
  675. cell.SetStyle(style)
  676. cell = row.AddCell()
  677. cell.SetValue("班次(第一班,第二班,第三班)")
  678. cell.SetStyle(style)
  679. cell = row.AddCell()
  680. cell.SetValue("收集时间")
  681. cell.SetStyle(style)
  682. cell = row.AddCell()
  683. cell.SetValue("操作人")
  684. cell.SetStyle(style)
  685. cell = row.AddCell()
  686. tx := restful.Engine.NewSession()
  687. defer tx.Close()
  688. dataList, err := tx.SQL(`select bname from bar where pastureid = (select column_default as pastureid from information_schema.COLUMNS
  689. WHERE table_name = 'recweight' AND table_schema = ? AND column_name = 'pastureid') order by sort ,id`, setting.DatabaseSetting.Name).Query().List()
  690. if err != nil {
  691. logs.Error("CronScheduled-error-1:", err)
  692. return
  693. }
  694. for _, data := range dataList {
  695. row = sheet.AddRow()
  696. cell = row.AddCell()
  697. cell.SetValue(data["bname"])
  698. cell.SetStyle(style)
  699. }
  700. c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  701. c.Header("Content-Disposition", "attachment; filename="+"栏舍剩料记录导入模板.xlsx")
  702. c.Header("Content-Transfer-Encoding", "binary")
  703. _ = file.Write(c.Writer)
  704. }
  705. func UploadFile1(c *gin.Context) {
  706. appG := app.Gin{C: c}
  707. pid := c.PostForm("pid")
  708. sort := c.PostForm("sort")
  709. isStart := c.PostForm("isStart")
  710. file, err := appG.C.FormFile("file")
  711. if err != nil {
  712. logs.Error(err)
  713. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  714. return
  715. }
  716. tx := restful.Engine.NewSession()
  717. defer tx.Close()
  718. fileInfoList, err := tx.SQL(` select startpicture,endpicture from downloadplandtl1_exec where pid = ? and sort = ? `, pid, sort).Query().List()
  719. if err != nil {
  720. logs.Error(err)
  721. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  722. return
  723. }
  724. if len(fileInfoList) > 0 {
  725. filepath := ""
  726. for _, fileinfo := range fileInfoList {
  727. if isStart == "1" {
  728. if _, ok := fileinfo["startpicture"]; ok {
  729. filepath = fileinfo["startpicture"].(string)
  730. }
  731. } else {
  732. if _, ok := fileinfo["endpicture"]; ok {
  733. filepath = fileinfo["endpicture"].(string)
  734. }
  735. }
  736. }
  737. os.Remove(filepath)
  738. }
  739. basePath := "uploads/image/"
  740. filename := basePath + filepath.Base(file.Filename)
  741. if err := appG.C.SaveUploadedFile(file, filename); err != nil {
  742. logs.Error(err)
  743. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  744. return
  745. }
  746. // filename = basePath + filepath.Base(file.Filename)
  747. if isStart == "1" {
  748. _, err = tx.SQL(` update downloadplandtl1_exec set startpicture = ? where pid = ? and sort = ? `, filename, pid, sort).Execute()
  749. if err != nil {
  750. logs.Error(err)
  751. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  752. return
  753. }
  754. } else {
  755. _, err = tx.SQL(` update downloadplandtl1_exec set endpicture = ? where pid = ? and sort = ? `, filename, pid, sort).Execute()
  756. if err != nil {
  757. logs.Error(err)
  758. appG.Response(http.StatusInternalServerError, e.ERROR, err)
  759. return
  760. }
  761. }
  762. appG.Response(http.StatusOK, e.SUCCESS, fmt.Sprintf("文件 %s 上传成功 ", file.Filename))
  763. }
  764. // func DownloadFile1(c *gin.Context) {
  765. // appG := app.Gin{C: c}
  766. // dataByte, _ := ioutil.ReadAll(c.Request.Body)
  767. // parammaps := gofasion.NewFasion(string(dataByte))
  768. // businessid := parammaps.Get("businessid").ValueStr()
  769. // tx := restful.Engine.NewSession()
  770. // defer tx.Close()
  771. // fileInfoList, err := tx.SQL(` select path from file where businessid = ? `, businessid).Query().List()
  772. // if err != nil {
  773. // logs.Error(err)
  774. // appG.Response(http.StatusInternalServerError, e.ERROR, err)
  775. // return
  776. // }
  777. // filepath := ""
  778. // for _, fileinfo := range fileInfoList {
  779. // filepath = fileinfo["path"].(string)
  780. // }
  781. // c.File(filepath)
  782. // }