12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package libs
- import (
- "strings"
- "encoding/base64"
- "time"
- "os"
- "strconv"
- "bufio"
- "github.com/astaxie/beego/logs"
- "wuyebaoxiuapi/contanst"
- )
- type ImageUpload struct {
- }
- const UPLOAD_DIR = "./static/upload/"
- func NewImageUpload() (*ImageUpload) {
- return new(ImageUpload)
- }
- func (this *ImageUpload)Upload(url string) (map[string]interface{}) {
- DataArr := strings.Split(url, ",")
- //去除包装,获取到base64编码
- imgBase64 := DataArr[1][:len(DataArr[1])-2]
- result := make(map[string]interface{})
- //base64转码
- imgs, err := base64.StdEncoding.DecodeString(imgBase64)
- if err != nil {
- logs.Debug("base64 decode error:", err)
- result["status"] = contanst.MSG_ERR
- result["message"] = ""
- result["image"] = ""
- return result
- }
- timenow := time.Now().Unix()
- file, err := os.OpenFile(UPLOAD_DIR+strconv.FormatInt(timenow, 10)+".jpg", os.O_CREATE|os.O_WRONLY, 0644)
- if err != nil {
- logs.Debug("create file error:", err)
- result["status"] = contanst.MSG_ERR
- result["message"] = ""
- result["image"] = ""
- return result
- }
- w := bufio.NewWriter(file) //创建新的 Writer 对象
- _, err3 := w.WriteString(string(imgs))
- if err3 != nil {
- logs.Debug("write error:", err3)
- result["status"] = contanst.MSG_ERR
- result["message"] = ""
- result["image"] = ""
- return result
- }
- w.Flush()
- defer file.Close()
- imgname := strconv.FormatInt(timenow, 10) + ".jpg"
- result["status"] = contanst.MSG_ERR
- result["image"] = imgname
- return result
- }
- func (this *ImageUpload)checkFileIsExist(filename string) bool {
- var exist = true
- if _, err := os.Stat(filename); os.IsNotExist(err) {
- exist = false
- }
- return exist
- }
|