Golang appengine-blobstore.ParseUpload类(方法)实例源码

下面列出了Golang appengine-blobstore.ParseUpload 类(方法)源码代码实例,从而了解它的用法。

作者:sellwee    项目:TOGY-serve   
//UploadHandler handles upload of a new presentation and saving its metadata
//to Datastore.
//
//Doesn't support filenames with non-ASCII characters. GAE encodes
//those into base-64 string with encoding prefixed and I don't want
//to include additional logic to differentiate between ASCII and
//non-ASCII filenames.
func UploadHandler(c util.Context) (err error) {
	blobs, formVal, err := blobstore.ParseUpload(c.R)
	if err != nil {
		return
	}
	blob := blobs["file"][0]
	fn := strings.Split(blob.Filename, ".")
	fileType := fn[len(fn)-1]

	var active bool
	if len(formVal["activate"]) == 0 {
		active = false
	} else {
		active = true
	}

	name := formVal["name"][0]
	if name == "" {
		name = "Neznáma prezentácia z " + time.Now().Format("2.1.2006")
	}

	p, err := presentation.Make(blob.BlobKey, fileType, name, []byte(formVal["description"][0]), active, c)
	if err != nil {
		return
	}

	http.Redirect(c.W, c.R, "/admin/presentation/"+p.Key().Encode(), 303)
	return
}

作者:dannys    项目:imagedatastor   
func handleDoUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		serveError(c, w, err)
		return
	}
	file := blobs["file"]
	if len(file) == 0 {
		c.Errorf("no file uploaded")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}

	img := Image{
		BlobKey: file[0].BlobKey,
	}

	key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "image", nil), &img)
	if err != nil {
		c.Errorf("datastore fail")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}

	http.Redirect(w, r, "/"+key.Encode(), http.StatusFound)
}

作者:mako071    项目:sampl   
// 画像のアップロード
func handleUploadImage(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "リクエストエラー", http.StatusBadRequest)
		return
	}
	c := appengine.NewContext(r)
	g := goon.FromContext(c)
	key := r.FormValue("key")
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	image := blobs["uploadFile"]
	if len(image) == 0 {
		http.Error(w, "画像がありません", http.StatusInternalServerError)
		return
	}
	ibi := ImageBlobInfo{
		Id:      key,
		BlobKey: string(image[0].BlobKey),
	}
	//	keys := datastore.NewIncompleteKey(c, "blobInfo", nil)
	//	_, err = datastore.Put(c, keys, &ibInfo)
	g.Put(&ibi)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write([]byte(ibi.BlobKey))
}

作者:TheAustrianPr    项目:overlay-tile   
// uploadHandler handles the image upload and stores a new Overlay in the
// datastore. If successful, it writes the Overlay's key to the response.
func uploadHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) *appError {
	// Handle the upload, and get the image's BlobKey.
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		return appErrorf(err, "could not parse blobs from blobstore upload")
	}
	b := blobs["overlay"]
	if len(b) < 1 {
		return appErrorf(nil, "could not find overlay blob")
	}
	bk := b[0].BlobKey

	// Fetch image from blob store to find its width and height.
	m, err := imageBlob(c, bk)
	if err != nil {
		return appErrorf(err, "could not get image")
	}

	// Create and store a new Overlay in the datastore.
	o := &Overlay{
		Owner:  user.Current(c).ID,
		Image:  bk,
		Width:  m.Bounds().Dx(),
		Height: m.Bounds().Dy(),
	}
	k := datastore.NewIncompleteKey(c, "Overlay", nil)
	k, err = datastore.Put(c, k, o)
	if err != nil {
		return appErrorf(err, "could not save new overlay to datastore")
	}

	// It will be known hereafter by its datastore-provided key.
	fmt.Fprintf(w, "%s", k.Encode())
	return nil
}

作者:hama    项目:av   
// Common function for uploading a file
func uploadFile(c appengine.Context, r *http.Request, currentFiles []model.File) ([]model.File, error) {
	// Parse file uploads
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		return currentFiles, err
	}
	files := blobs["file"]
	if len(files) == 0 {
		c.Errorf("no file uploaded")
		return currentFiles, nil
	}

	// Add the new file
	for i := range files {
		newFile := model.File{files[i].Filename, files[i].BlobKey}

		// Check if it already exists
		exists := false
		for j := range currentFiles {
			if currentFiles[j].Filename == newFile.Filename {
				// Overwrite
				// TODO: delete the old file
				currentFiles[j] = newFile
				exists = true
				break
			}
		}

		if !exists {
			currentFiles = append(currentFiles, newFile)
		}
	}

	return currentFiles, nil
}

作者:ssaavedr    项目:elpa-on-appengin   
func upload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	file := blobs["file"]
	if len(file) == 0 {
		c.Errorf("No file uploaded")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	reader := blobstore.NewReader(c, file[0].BlobKey)
	var pkg *Package
	switch file[0].ContentType {
	case "application/x-tar":
		pkg, err = parsePackageVarsFromTar(bufio.NewReader(reader))
		if err == nil {
			pkg.Type = TAR
		}
	case "application/octet-stream":
		pkg, err = parsePackageVarsFromFile(bufio.NewReader(reader))
		if err == nil {
			pkg.Type = SINGLE
		}
	default:
		http.Error(w, err.Error(), http.StatusBadRequest)
	}

	if err != nil {
		c.Errorf(fmt.Sprintf("Error reading from upload: %v", err))
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	key := packageKey(c, pkg.Name)
	_, err = datastore.Put(c, key, pkg)
	if err != nil {
		c.Errorf(fmt.Sprintf("Failed to save package %v", pkg.Name))
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	contents := Contents{
		BlobKey:    file[0].BlobKey,
		Version:    pkg.LatestVersion,
		UploadTime: time.Now().UTC(),
	}
	_, err = datastore.Put(c, versionKey(c, pkg.LatestVersion, key), &contents)
	if err != nil {
		c.Errorf(
			fmt.Sprintf(
				"Failed to save contents for version %v, package %v",
				pkg.LatestVersion, pkg.Name))
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/upload_complete.html?package="+
		url.QueryEscape(pkg.Name), http.StatusFound)
}

作者:nickdufresn    项目:GAE-Billing-Syste   
func handleCreateBill(ctx *Context, w http.ResponseWriter, r *http.Request) error {
	errs := []string{}

	blobs, fields, err := blobstore.ParseUpload(ctx.r)

	ctx.Debugf("Blobs: %v", blobs)

	if err != nil {
		return err
	}

	//vendor := getFormFieldString(fields, "vendor")
	amt := getFormFieldInt(fields, "amount")
	if amt <= 0 {
		errs = append(errs, "Amount must be greater than 0")
	}

	vendorID := getFormFieldString(fields, "vendor")
	if vendorID == "" {
		errs = append(errs, "You must choose a vendor for the bill")
	}

	file := blobs["file"]
	if len(file) == 0 {
		errs = append(errs, "You must upload a bill file")
	}

	if len(errs) > 0 {
		return renderBillForm(ctx, errs)
	}

	v, err := ctx.GetVendorByID(vendorID)

	if err != nil {
		return err
	}

	b := Bill{
		Amt:        amt,
		PostedOn:   time.Now(),
		VendorKey:  v.Key,
		CompanyKey: v.CompanyKey,
		PostedBy:   ctx.user.String(),
		BlobKey:    file[0].BlobKey,
	}

	key := datastore.NewIncompleteKey(ctx.c, "Bill", v.CompanyKey)
	_, err = datastore.Put(ctx.c, key, &b)
	if err != nil {
		return err
	}
	ctx.Flash("New bill created successfully!")
	return ctx.Redirect("/admin/bills")
}

作者:TomiHiltune    项目:GAE-Go-image-optimize   
/*
 * This one does the magic.
 *
 *      - Gets the uploaded blobs by calling blobstore.ParseUpload()
 *      - Maintains all other values that come from blobstore.
 *      - Hands out the results for further processing.
 */
func ParseBlobs(options *compressionOptions) (blobs map[string][]*blobstore.BlobInfo, other url.Values, err error) {
	blobs, other, err = blobstore.ParseUpload(options.Request)
	if err != nil {
		return
	}
	// Loop through all the blob names
	for keyName, blobSlice := range blobs {
		blobs[keyName] = handleBlobSlice(options, blobSlice)
	}
	return
}

作者:phytho    项目:boyd-searc   
func UploadHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, _ := user.LoginURL(c, r.URL.String())
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}

	id := r.FormValue("id")
	if len(id) > 0 {
		w.Header().Set("Location", "/upload2?id=has_key:"+id)
		w.WriteHeader(http.StatusFound)
		//    uploadTemplate.Execute(w, id)
		return
	}

	blobs, other_params, err := blobstore.ParseUpload(r)
	if len(blobs) == 0 {
		//    w.WriteHeader(http.StatusBadRequest)
		//    fmt.Fprintf(w, "No data '%v'", err)
		w.Header().Set("Location", "/upload2?id=Bad+upload:"+err.String())
		w.WriteHeader(http.StatusFound)
		return
	}
	file := blobs["file_data"]
	if len(file) == 0 {
		//    w.WriteHeader(http.StatusBadRequest)
		//    fmt.Fprintf(w, "No data")
		w.Header().Set("Location", "/upload2?id=No_file_data")
		w.WriteHeader(http.StatusFound)
		return
	}

	key := string(file[0].BlobKey)
	if other_params == nil {
		other_params = make(map[string][]string)
	}
	other_params["key"] = append(other_params["key"], key)
	task := taskqueue.NewPOSTTask("/process/gedcom", other_params)
	task.Name = key
	if err := taskqueue.Add(c, task, ""); err != nil {
		//    http.Error(w, err.String(), http.StatusInternalServerError)
		w.Header().Set("Location", "/upload2?id=bad_task:"+err.String())
		w.WriteHeader(http.StatusFound)
		return
	}

	w.Header().Set("Location", "/upload?id="+key)
	w.WriteHeader(http.StatusFound)
	return
}

作者:aarzill    项目:tool   
func blobAutoUpload(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	// Here we just checked that the upload went through as expected.
	if _, _, err := blobstore.ParseUpload(r); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		c.Errorf("%s", err)
		return
	}
	// Everything seems fine. Signal the other handler using the status code.
	w.WriteHeader(http.StatusCreated)
}

作者:ashishthede    项目:climatic_webap   
func (x UploadRes) Post(c appengine.Context, r *http.Request) (interface{}, error) {
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		return nil, err
	}
	file := blobs["file"]
	if len(file) == 0 {
		return nil, fmt.Errorf("No file uploaded")
	}
	bk := file[0].BlobKey
	PrintInBox(c, "File saved with blobkey", bk)
	return bk, nil
}

作者:ghostnote    项目:HelloG   
func handleUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		serveError(c, w, err)
		return
	}
	file := blobs["file"]
	if len(file) == 0 {
		c.Errorf("no file uploaded")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}

作者:ninneman    项目:dynamicfa   
func Save(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	ctx := appengine.NewContext(req)

	blobs, vals, err := blobstore.ParseUpload(req)
	if err != nil {
		http.Redirect(rw, req, "/admin/content/"+params["id"]+"?error="+err.Error(), http.StatusFound)
		return
	}

	var title string
	var body string
	var link string
	if len(vals["title"]) > 0 {
		title = vals["title"][0]
	}
	if len(vals["body"]) > 0 {
		body = vals["body"][0]
	}
	if len(vals["link"]) > 0 {
		link = vals["link"][0]
	}

	c := content.Content{}

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		c.ID = int64(intID)
	}

	c.Get(ctx)
	c.Title = title
	c.Body = body
	c.Link = link

	file := blobs["image"]
	if len(file) != 0 {
		c.Image = fmt.Sprintf("/blob/%s", string(file[0].BlobKey))
	}

	err = c.Save(ctx)
	if err != nil {
		http.Redirect(rw, req, "/admin/content/"+params["id"]+"?error="+err.Error(), http.StatusFound)
		return
	}

	http.Redirect(rw, req, "/admin/content/"+strconv.Itoa(int(c.ID))+"?success=Content saved", http.StatusFound)
	return
}

作者:henglinl    项目:goblo   
func handleUpload(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if r.Method != "POST" || r.URL.Path != "/upload" {
		serve404(w)
		return
	}
	c := appengine.NewContext(r)
	blobs, _, err := blobstore.ParseUpload(r)
	if nil != err {
		serveError(c, w, err)
		return
	}
	file := blobs["file"]
	if len(file) == 0 {
		http.Error(w, "No File upload!", http.StatusInternalServerError)
		return
	}
	switch file[0].ContentType {
	/*
	 case "text/xml":
	 page, err := updatePage(c, file[0].BlobKey)
	 if nil != err {
	 serve404(w)
	 return
	 }
	 err = updateTag(c, page)
	 if nil != err {
	 serveError(c, w, err)
	 return
	 }
	 http.Redirect(w, r, "/pages?Title="+page.Title, http.StatusFound)
	*/
	case "image/jpeg", "image/png", "image/webp", "image/gif", "image/bmp", "image/tiff", "image/ico":
		image := Image{file[0].Filename, file[0].BlobKey}
		err = updateImage(c, image)
		if nil != err {
			serveError(c, w, err)
			return
		}
		http.Redirect(w, r, "/images?Name="+file[0].Filename, http.StatusFound)
	default:
		err := errors.New("ContentType " + file[0].ContentType + " not supported!")
		//http.Error(w, "ContentType "+ file[0].ContentType + " not supported!", http.StatusInternalServerError)
		serveError(c, w, err)
	}
	// http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}

作者:alvaradopcesa    项目:gae-go-exampl   
func BlobUpload(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	file := blobs["file"]
	if len(file) == 0 {
		c.Errorf("no file upload")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	http.Redirect(w, r, "/blob/store?blobkey="+string(file[0].BlobKey), http.StatusFound)
}

作者:ninneman    项目:dynamicfa   
func Save(rw http.ResponseWriter, req *http.Request, r render.Render, params martini.Params) {
	ctx := appengine.NewContext(req)

	blobs, vals, err := blobstore.ParseUpload(req)
	if err != nil {
		http.Redirect(rw, req, "/admin/banners/"+params["id"]+"?error="+err.Error(), http.StatusFound)
		return
	}

	var title string
	var caption string
	if len(vals["title"]) > 0 {
		title = vals["title"][0]
	}
	if len(vals["caption"]) > 0 {
		caption = vals["caption"][0]
	}

	b := banner.Banner{}

	intID, err := strconv.Atoi(params["id"])
	if err == nil {
		b.ID = int64(intID)
	}

	b.Get(ctx)
	b.Title = title
	b.Caption = caption

	file := blobs["image"]
	if len(file) != 0 {
		b.Image = fmt.Sprintf("/blob/%s", string(file[0].BlobKey))
	} else if intID == 0 {
		http.Redirect(rw, req, "/admin/banners/"+params["id"]+"?error=You must upload an image", http.StatusFound)
		return
	}

	err = b.Save(ctx)
	if err != nil {
		http.Redirect(rw, req, "/admin/banners/"+params["id"]+"?error="+err.Error(), http.StatusFound)
		return
	}

	http.Redirect(rw, req, "/admin/banners/"+strconv.Itoa(int(b.ID))+"?success=Banner saved", http.StatusFound)
	return
}

作者:kwilliams8    项目:nomada   
func storeImage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if err := users.CheckPerm(w, r, users.OP_UPDATE); err != nil {
		return
	}

	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		app.ServeError(c, w, err)
		return
	}

	file := blobs["img"]
	if len(file) == 0 {
		app.ServeError(c, w, errors.New(ERR_FILENOTSTORED))
		return
	}

	key := file[0].BlobKey

	info, err := blobstore.Stat(c, key)
	if err != nil {
		app.ServeError(c, w, err)
		return
	}

	if info.Size > MAXSZIMAGE {
		blobstore.Delete(c, key)
		app.ServeError(c, w, errors.New(ERR_FILENOTVALID))
		return
	}

	/*

		key,err=resizeImage(c,key)
		if err != nil {
	                app.ServeError(c, w, errors.New(ERR_FILENOTVALID))
	                return
	        }

	*/

	fmt.Fprintf(w, "%s", string(key))
}

作者:jbeshi    项目:dreampics_fronten   
func HandleUpload(r *http.Request) (storageName string, other url.Values, err error) {
	blobs, other, err := blobstore.ParseUpload(r)
	if err != nil {
		return "", nil, err
	}

	// Delete any uploads other than the one we actually want.
	// Stops users from wasting our storage for no reason.
	var deleteList []string
	for k, fileList := range blobs {
		for i, file := range fileList {
			if k != "file" || i != 0 {
				deleteList = append(deleteList, file.ObjectName)
			}
		}
	}
	if len(deleteList) > 0 {

		c := appengine.NewContext(r)
		ctx, err := getGcsContext(c)
		if err != nil {
			return "", nil, err
		}

		for _, junk := range deleteList {

			// If one of our delete ops fails, still try the rest,
			// but set err aside, preserving it, so we can return
			// after.
			if newErr := storage.DeleteObject(ctx, gcsBucket, junk); err != nil {
				err = newErr
			}
		}
	}
	if err != nil {
		return "", nil, err
	}

	if len(blobs["file"]) == 0 {
		return "", nil, errors.New("No file uploaded.")
	}

	return blobs["file"][0].ObjectName, other, nil
}

作者:vmihailenc    项目:goblo   
func ArticleCreateHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	user := core.AdminUser(c, w)
	if user == nil {
		return
	}

	form := NewArticleForm(nil)

	if r.Method == "POST" {
		blobs, values, err := blobstore.ParseUpload(r)
		if err != nil {
			core.HandleError(c, w, err)
			return
		}

		if gaeforms.IsBlobstoreFormValid(form, blobs, values) {
			article, err := CreateArticle(c,
				form.Title.Value(),
				form.Text.Value(),
				form.IsPublic.Value(),
			)
			if err != nil {
				core.HandleError(c, w, err)
				return
			}

			redirectTo, err := article.URL()
			if err != nil {
				core.HandleError(c, w, err)
				return
			}
			http.Redirect(w, r, redirectTo.Path, 302)
		}
	}

	context := map[string]interface{}{
		"form": form,
	}
	core.RenderTemplate(c, w, context,
		"templates/blog/articleCreate.html", "templates/blog/articleForm.html", LAYOUT)
}

作者:huluw    项目:2016_Gof   
func importOPML(pfc *PFContext) (interface{}, error) {
	c := pfc.C
	r := pfc.R

	blobs, other, err := blobstore.ParseUpload(r)
	if err != nil {
		return nil, NewReadableError(_l("Error receiving file"), &err)
	} else if len(other["client"]) > 0 {
		if clientID := other["client"][0]; clientID != "" {
			pfc.ChannelID = string(pfc.UserID) + "," + clientID
		}
	}

	var blobKey appengine.BlobKey
	if blobInfos := blobs["opml"]; len(blobInfos) == 0 {
		return nil, NewReadableError(_l("File not uploaded"), nil)
	} else {
		blobKey = blobInfos[0].BlobKey
		reader := blobstore.NewReader(c, blobKey)

		if _, err := rss.ParseOPML(reader); err != nil {
			if err := blobstore.Delete(c, blobKey); err != nil {
				c.Warningf("Error deleting blob (key %s): %s", blobKey, err)
			}

			return nil, NewReadableError(_l("Error reading OPML file"), &err)
		}
	}

	params := taskParams{
		"opmlBlobKey": string(blobKey),
	}
	if err := startTask(pfc, "import", params, importQueue); err != nil {
		// Remove the blob
		if err := blobstore.Delete(c, blobKey); err != nil {
			c.Warningf("Error deleting blob (key %s): %s", blobKey, err)
		}

		return nil, NewReadableError(_l("Cannot import - too busy"), &err)
	}

	return _l("Importing, please wait…"), nil
}


问题


面经


文章

微信
公众号

扫码关注公众号