Beispiel #1
0
func uploadBufWithoutKeyDemo(r gio.Reader, key, uptoken string) {
	// @gist uploadBufWithoutKey
	var err error
	var ret io.PutRet
	var extra = &io.PutExtra{
	// Params:   params,
	// MimeType: mieType,
	// Crc32:    crc32,
	// CheckCrc: CheckCrc,
	}

	// ret       变量用于存取返回的信息,详情见 io.PutRet
	// uptoken   为业务服务器端生成的上传口令
	// r         为io.Reader类型,用于从其读取数据
	// extra     为上传文件的额外信息,可为空, 详情见 io.PutExtra, 可选
	err = io.PutWithoutKey(nil, &ret, uptoken, r, extra)

	if err != nil {
		//上传产生错误
		log.Print("io.Put failed:", err)
		return
	}

	//上传成功,处理返回值
	log.Print(ret.Hash, ret.Key)
	// @endgist
}
Beispiel #2
0
//upload user avatar
func UploadUserAvatarToQiniu(r io.ReadSeeker, filename string, mime string, bucketName string, user *models.User) error {
	var ext string

	// test image mime type
	switch mime {
	case "image/jpeg":
		ext = ".jpg"

	case "image/png":
		ext = ".png"

	case "image/gif":
		ext = ".gif"

	default:
		ext = filepath.Ext(filename)
		switch ext {
		case ".jpg", ".png", ".gif":
		default:
			return fmt.Errorf("unsupport image format `%s`", filename)
		}
	}

	// decode image
	var err error
	switch ext {
	case ".jpg":
		_, err = jpeg.Decode(r)
	case ".png":
		_, err = png.Decode(r)
	case ".gif":
		_, err = gif.Decode(r)
	}

	if err != nil {
		return err
	}

	//reset reader pointer
	if _, err := r.Seek(0, 0); err != nil {
		return err
	}
	var data []byte
	if data, err = ioutil.ReadAll(r); err != nil {
		return err
	}

	if len(data) > setting.AvatarImageMaxLength {
		return fmt.Errorf("avatar image size too large", filename)
	}

	//reset reader pointer again
	if _, err := r.Seek(0, 0); err != nil {
		return err
	}

	//save to qiniu
	var uptoken = utils.GetQiniuUptoken(bucketName)
	var putRet qio.PutRet
	var putExtra = &qio.PutExtra{
		MimeType: mime,
	}

	err = qio.PutWithoutKey(nil, &putRet, uptoken, r, putExtra)
	if err != nil {
		return err
	}

	//update user
	user.AvatarKey = putRet.Key
	if err := user.Update("AvatarKey", "Updated"); err != nil {
		return err
	}
	return nil
}