upload.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package libs
  2. import (
  3. "strings"
  4. "encoding/base64"
  5. "time"
  6. "os"
  7. "strconv"
  8. "bufio"
  9. "github.com/astaxie/beego/logs"
  10. "wuyebaoxiuapi/contanst"
  11. )
  12. type ImageUpload struct {
  13. }
  14. const UPLOAD_DIR = "./static/upload/"
  15. func NewImageUpload() (*ImageUpload) {
  16. return new(ImageUpload)
  17. }
  18. func (this *ImageUpload)Upload(url string) (map[string]interface{}) {
  19. DataArr := strings.Split(url, ",")
  20. //去除包装,获取到base64编码
  21. imgBase64 := DataArr[1][:len(DataArr[1])-2]
  22. result := make(map[string]interface{})
  23. //base64转码
  24. imgs, err := base64.StdEncoding.DecodeString(imgBase64)
  25. if err != nil {
  26. logs.Debug("base64 decode error:", err)
  27. result["status"] = contanst.MSG_ERR
  28. result["message"] = ""
  29. result["image"] = ""
  30. return result
  31. }
  32. timenow := time.Now().Unix()
  33. file, err := os.OpenFile(UPLOAD_DIR+strconv.FormatInt(timenow, 10)+".jpg", os.O_CREATE|os.O_WRONLY, 0644)
  34. if err != nil {
  35. logs.Debug("create file error:", err)
  36. result["status"] = contanst.MSG_ERR
  37. result["message"] = ""
  38. result["image"] = ""
  39. return result
  40. }
  41. w := bufio.NewWriter(file) //创建新的 Writer 对象
  42. _, err3 := w.WriteString(string(imgs))
  43. if err3 != nil {
  44. logs.Debug("write error:", err3)
  45. result["status"] = contanst.MSG_ERR
  46. result["message"] = ""
  47. result["image"] = ""
  48. return result
  49. }
  50. w.Flush()
  51. defer file.Close()
  52. imgname := strconv.FormatInt(timenow, 10) + ".jpg"
  53. result["status"] = contanst.MSG_ERR
  54. result["image"] = imgname
  55. return result
  56. }
  57. func (this *ImageUpload)checkFileIsExist(filename string) bool {
  58. var exist = true
  59. if _, err := os.Stat(filename); os.IsNotExist(err) {
  60. exist = false
  61. }
  62. return exist
  63. }