golang上传图片文件到七牛云

由于七牛官方给出的golang sdk示例中只有本地文件,字符串流上传方式的示例代码,唯独缺少实际开发中直接上传文件流到七牛云存储的方式。实际开发中,都是前端页面通过表单方式提交文件数据到后端接口,后端不应该是先将文件保存到服务器再上传到七牛,而是应该直接以二进制流的方式上传到七牛云存储;

package controllers

import (
	"fmt"
	"gitee.com/idart/gohistory/libs"
	"github.com/kataras/iris"
	"github.com/kataras/iris/sessions"
	config "github.com/spf13/viper"
	"log"
)

type ResultController struct {
	Ctx     iris.Context
	Session *sessions.Session
}

type Result struct {
	Status   bool        `json:"status"`
	Code     int         `json:"code"`
	Mag      interface{} `json:"msg"`
	Data     interface{} `json:"data"`
	FilePath string      `json:"file_path"`
}

func ApiResult(status bool, code int, msg interface{}, filePath string, data interface{}) (result *Result) {
	result = &Result{Status: status, Code: code, Mag: msg, Data: data, FilePath: filePath}
	return
}

func (c *ResultController) PostFile() {
	f, h, err := c.Ctx.FormFile("image")
	if err != nil {
		c.Ctx.JSON(ApiResult(false, 400, "文件上传失败", "", ""))
		return
	}
	defer f.Close()
	file, err := h.Open()
	//buffer := make([]byte, 5<<20)
	//fileLength, err := f.Read(buffer)

	if err != nil {
		panic(err)
	}
	//else {
	//	fmt.Println("读取了", fileLength, "字节内容")
	//}

	config.SetConfigName("qiniu")
	if err := config.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file, %s", err)
	}
	staticDomain := config.GetString("default.domain")
	fileKey, err := libs.UploadToQiniu(file, h.Size)
	fileurl := staticDomain + fileKey
	fmt.Println(fileurl)
	if err == nil {
		c.Ctx.JSON(ApiResult(true, 200, "文件上传成功", fileurl, ""))
	} else {
		c.Ctx.JSON(ApiResult(false, 400, "文件上传失败", "", ""))
	}
	return
}

func UploadToQiniu(byteData io.Reader, size int64) (string, error) {
	config.SetConfigName("qiniu")
	if err := config.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file, %s", err)
	}
	accessKey := config.GetString("default.accessKey")
	secretKey := config.GetString("default.secretKey")
	bucket := config.GetString("default.bucket")
	u1 := uuid.NewV4()
	temKey := fmt.Sprintf("UUIDv4: %s", u1)
	key := strings.Split(temKey, " ")[1]
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)
	fmt.Println(upToken)
	cfg := storage.Config{}
	cfg.Zone = &storage.ZoneHuabei
	cfg.UseHTTPS = false
	cfg.UseCdnDomains = false

	//构建代理client对象
	client := http.Client{}

	// 构建表单上传的对象
	formUploader := storage.NewFormUploaderEx(&cfg, &storage.Client{Client: &client})
	ret := storage.PutRet{}
	// 可选配置
	putExtra := storage.PutExtra{}
	err := formUploader.Put(context.Background(), &ret, upToken, key, byteData, size, &putExtra)
	//err := formUploader.Put(context.Background(), &ret, upToken, key, bytes.NewReader(data), dataLen, &putExtra)
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	return ret.Key, nil
}

参考文章地址:

  https://segmentfault.com/a/1190000017761515

Top