func UploadFile(dir string, read io.Reader) (string, error) { ACCESS_KEY = Webconfig.UploadConfig.QiniuAccessKey SECRET_KEY = Webconfig.UploadConfig.QiniuSecretKey extra := &qiniu_io.PutExtra{ // Bucket: "messagedream", MimeType: "", } var policy = rs.PutPolicy{ Scope: "messagedream", } filename := strings.Replace(UUID(), "-", "", -1) + ".jpg" body, _ := ioutil.ReadAll(read) h := md5.New() h.Write(body) key := "static/upload/" + dir + "/" + filename ret := new(qiniu_io.PutRet) buf := bytes.NewBuffer(body) return key, qiniu_io.Put(nil, ret, policy.Token(nil), key, buf, extra) }
func TestPutFile(t *testing.T) { token, key := GetToken() ret := io.PutRet{} extra := &io.PutExtra{} r := bytes.NewBufferString("hello qiniu") if err := io.Put(nil, &ret, token, key, r, extra); err != nil { fmt.Println(err) return } fmt.Println(ret) url := GetUrl(key) resp, err := http.Get(url) if err != nil { fmt.Println(err) return } body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
func uploadBufDemo(r gio.Reader, key, uptoken string) { // @gist uploadBuf var err error var ret io.PutRet var extra = &io.PutExtra{ // Params: params, // MimeType: mieType, // Crc32: crc32, // CheckCrc: CheckCrc, } // ret 变量用于存取返回的信息,详情见 io.PutRet // uptoken 为业务服务器端生成的上传口令 // key 为文件存储的标识 // r 为io.Reader类型,用于从其读取数据 // extra 为上传文件的额外信息,可为空, 详情见 io.PutExtra, 可选 err = io.Put(nil, &ret, uptoken, key, r, extra) if err != nil { //上传产生错误 log.Print("io.Put failed:", err) return } //上传成功,处理返回值 log.Print(ret.Hash, ret.Key) // @endgist }
func UploadAvatar(file *os.File, key string) error { // 生成 uploadToken, string类型 uploadToken := policy.Token() // 声明 PutExtra extra := &qiniuIo.PutExtra{ // [string] 必选, 指定上传的目标仓库 Bucket: "hellogolang", // [string] 可选。在 uptoken 没有指定 DetectMime 时,用户客户端可自己指定 MimeType MimeType: "", // [string] 可选。用户自定义 Meta,不能超过 256 字节 CustomMeta: "", // [string] 当 uptoken 指定了 CallbackUrl,则 CallbackParams 必须非空 CallbackParams: "", } ret := new(qiniuIo.PutRet) err := qiniuIo.Put(nil, ret, uploadToken, key, file, extra) // PutRet, error if err != nil { // 上传失败 fmt.Println(err) return err } return nil }
// URL: /upload/image // 编辑器上传图片,接收后上传到七牛 func uploadImageHandler(handler *Handler) { file, header, err := handler.Request.FormFile("editormd-image-file") if err != nil { panic(err) return } defer file.Close() // 检查是否是jpg或png文件 uploadFileType := header.Header["Content-Type"][0] filenameExtension := "" if uploadFileType == "image/jpeg" { filenameExtension = ".jpg" } else if uploadFileType == "image/png" { filenameExtension = ".png" } else if uploadFileType == "image/gif" { filenameExtension = ".gif" } if filenameExtension == "" { handler.ResponseWriter.Header().Set("Content-Type", "text/html") handler.ResponseWriter.Write(editorMdUploadImageResult(0, "", "不支持的文件格式,请上传 jpg/png/gif 图片")) return } // 上传到七牛 // 文件名:32位uuid+后缀组成 filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + filenameExtension key := "upload/image/" + filename ret := new(qiniuIo.PutRet) var policy = rs.PutPolicy{ Scope: "gopher", } err = qiniuIo.Put( nil, ret, policy.Token(nil), key, file, nil, ) if err != nil { panic(err) handler.ResponseWriter.Header().Set("Content-Type", "text/html") handler.ResponseWriter.Write(editorMdUploadImageResult(0, "", "图片上传到七牛失败")) return } handler.ResponseWriter.Header().Set("Content-Type", "text/html") handler.ResponseWriter.Write(editorMdUploadImageResult(1, "http://7xj1eq.com1.z0.glb.clouddn.com/"+key, "")) }
func qiniuUploadImage(file *multipart.File, fileName string) (error, qio.PutRet) { var ret qio.PutRet var policy = rs.PutPolicy{ Scope: models.QiniuScope, } err := qio.Put(nil, &ret, policy.Token(nil), fileName, *file, nil) if err != nil { revel.ERROR.Println("io.Put failed:", err) } return err, ret }
func main() { ACCESS_KEY = gopher.Config.QiniuAccessKey SECRET_KEY = gopher.Config.QiniuSecretKey extra := &qiniu_io.PutExtra{ Bucket: "gopher", MimeType: "", CustomMeta: "", CallbackParams: "", } var policy = rs.PutPolicy{ Scope: "gopher", } c := gopher.DB.C("users") var users []gopher.User c.Find(nil).All(&users) for _, user := range users { url := webhelpers.Gravatar(user.Email, 256) resp, err := http.Get(url) if err != nil { fmt.Println("get gravatar image error:", url, err.Error()) return } filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + ".jpg" body, _ := ioutil.ReadAll(resp.Body) h := md5.New() h.Write(body) md5Str := fmt.Sprintf("%x", h.Sum(nil)) if md5Str != "ac83818c6d5b6aca4b6f796b6d3cb338" { // 不是默认头像,上传 key := "avatar/" + filename ret := new(qiniu_io.PutRet) buf := bytes.NewBuffer(body) err = qiniu_io.Put(nil, ret, policy.Token(), key, buf, extra) if err == nil { c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"avatar": filename}}) fmt.Printf("upload %s's avatar success: %s\n", user.Email, filename) } else { fmt.Printf("upload %s' avatar error: %s\n", user.Email, err.Error()) } } resp.Body.Close() } }
func TestDeleteFile(t *testing.T) { token, key := GetToken() ret := io.PutRet{} extra := &io.PutExtra{} r := bytes.NewBufferString("hello qiniu") if err := io.Put(nil, &ret, token, key, r, extra); err != nil { fmt.Println(err) return } SetFileExpiredTime(key, 2) SetFileExpiredTime("no_exist_file", 3) time.Sleep(time.Second * 5) }
// 上传到七牛,并返回文件名 func uploadAvatarToQiniu(file io.ReadCloser, contentType string) (filename string, err error) { isValidateType := false for _, imgType := range []string{"image/png", "image/jpeg"} { if imgType == contentType { isValidateType = true break } } if !isValidateType { return "", errors.New("文件类型错误") } filenameExtension := ".jpg" if contentType == "image/png" { filenameExtension = ".png" } // 文件名:32位uuid,不带减号和后缀组成 filename = strings.Replace(uuid.NewUUID().String(), "-", "", -1) + filenameExtension ACCESS_KEY = Config.QiniuAccessKey SECRET_KEY = Config.QiniuSecretKey key := "avatar/" + filename ret := new(qiniu_io.PutRet) var policy = rs.PutPolicy{ Scope: "gopher", } err = qiniu_io.Put( nil, ret, policy.Token(nil), key, file, nil, ) if err != nil { return "", err } return filename, nil }
func UploadMemoryFile(r gio.Reader, key string) (err error) { InitQiniu() var ret io.PutRet var extra = &io.PutExtra{ // Params: params, // MimeType: mieType, // Crc32: crc32, // CheckCrc: CheckCrc, } // ret 变量用于存取返回的信息,详情见 io.PutRet // uptoken 为业务服务器端生成的上传口令 // key 为文件存储的标识 // r 为io.Reader类型,用于从其读取数据 // extra 为上传文件的额外信息,可为空, 详情见 io.PutExtra, 可选 err = io.Put(nil, &ret, uptoken, key, r, extra) // 上传产生错误 if err != nil { logger.Errorln("io.Put failed:", err) errInfo := make(map[string]interface{}) err = json.Unmarshal([]byte(err.Error()), &errInfo) if err != nil { logger.Errorln("io.Put Unmarshal failed:", err) return } code, ok := errInfo["code"] if ok && code == 614 { err = nil } return } // 上传成功,处理返回值 logger.Debugln(ret.Hash, ret.Key) return }
// URL: /profile/avatar // 修改头像,提交到七牛云存储 func changeAvatarHandler(w http.ResponseWriter, r *http.Request) { user, ok := currentUser(r) if !ok { http.Redirect(w, r, "/signin?next=/profile/avatar", http.StatusFound) return } if r.Method == "POST" { formFile, formHeader, err := r.FormFile("file") if err != nil { fmt.Println("changeAvatarHandler:", err.Error()) renderTemplate(w, r, "account/avatar.html", map[string]interface{}{ "user": user, "error": "请选择图片上传", }) return } defer formFile.Close() // 检查是否是jpg或png文件 uploadFileType := formHeader.Header["Content-Type"][0] isValidateType := false for _, imgType := range []string{"image/png", "image/jpeg"} { if imgType == uploadFileType { isValidateType = true break } } if !isValidateType { fmt.Println("upload image type error:", uploadFileType) // 提示错误 renderTemplate(w, r, "account/avatar.html", map[string]interface{}{ "user": user, "error": "文件类型错误,请选择jpg/png图片上传。", }) return } // 检查文件尺寸是否在500K以内 fileSize := formFile.(Sizer).Size() if fileSize > 500*1024 { // > 500K fmt.Printf("upload image size > 500K: %dK\n", fileSize/1024) renderTemplate(w, r, "account/avatar.html", map[string]interface{}{ "user": user, "error": "图片大小大于500K,请选择500K以内图片上传。", }) return } extra := &qiniu_io.PutExtra{ Bucket: "gopher", MimeType: "", CustomMeta: "", CallbackParams: "", } ACCESS_KEY = Config.QiniuAccessKey SECRET_KEY = Config.QiniuSecretKey filenameExtension := ".jpg" if uploadFileType == "image/png" { filenameExtension = ".png" } // 文件名:32位uuid,不带减号和后缀组成 filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + filenameExtension key := "avatar/" + filename ret := new(qiniu_io.PutRet) var policy = rs.PutPolicy{ Scope: "gopher", } err = qiniu_io.Put(nil, ret, policy.Token(), key, formFile, extra) if err != nil { fmt.Println("upload to qiniu failed:", err.Error()) renderTemplate(w, r, "account/avatar.html", map[string]interface{}{ "user": user, "error": "上传失败,请反馈错误", }) return } // 存储远程文件名 c := DB.C("users") c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"avatar": filename}}) http.Redirect(w, r, "/profile#avatar", http.StatusFound) return } renderTemplate(w, r, "account/avatar.html", map[string]interface{}{"user": user}) }
func SaveImageToQiniu(m *models.Image, r goio.ReadSeeker, mime string, filename string, created time.Time, bucketName string) error { var ext string // check 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 img image.Image var err error switch ext { case ".jpg": m.Ext = 1 img, err = jpeg.Decode(r) case ".png": m.Ext = 2 img, err = png.Decode(r) case ".gif": m.Ext = 3 img, err = gif.Decode(r) } if err != nil { return err } m.Width = img.Bounds().Dx() m.Height = img.Bounds().Dy() m.Created = created //save to database if err := models.Insert(m); err != nil || m.Id <= 0 { return err } m.Token = m.GetToken() if err := models.UpdateById(m.Id, m); err != nil { return err } var key = m.Token //reset reader pointer if _, err := r.Seek(0, 0); err != nil { return err } //save to qiniu var uptoken = utils.GetQiniuUptoken(bucketName) var putRet io.PutRet var putExtra = &io.PutExtra{ MimeType: mime, } err = io.Put(nil, &putRet, uptoken, key, r, putExtra) if err != nil { return err } return nil }
// URL: /upload/image // 编辑器上传图片,接收后上传到七牛 func uploadImageHandler(handler *Handler) { defer dps.Persist() file, header, err := handler.Request.FormFile("editormd-image-file") if err != nil { panic(err) return } defer file.Close() // 检查是否是jpg或png文件 uploadFileType := header.Header["Content-Type"][0] filenameExtension := "" if uploadFileType == "image/jpeg" { filenameExtension = ".jpg" } else if uploadFileType == "image/png" { filenameExtension = ".png" } else if uploadFileType == "image/gif" { filenameExtension = ".gif" } if filenameExtension == "" { handler.renderJson(map[string]interface{}{ "success": 0, "message": "不支持的文件格式,请上传 jpg/png/gif 图片", }) return } // 上传到七牛 // 文件名:32位uuid+后缀组成 filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + filenameExtension key := "upload/image/" + filename ret := new(qiniuIo.PutRet) var policy = rs.PutPolicy{ Scope: "gopher", } err = qiniuIo.Put( nil, ret, policy.Token(nil), key, file, nil, ) if err != nil { panic(err) handler.renderJson(map[string]interface{}{ "success": 0, "message": "图片上传到七牛失败", }) return } handler.renderJson(map[string]interface{}{ "success": 1, "url": "http://gopher.qiniudn.com/" + key, }) }