func (a *GaeDatastoreAccessor) processUploadFile(r *http.Request, name string) (string, map[string][]string, error) {
	// See https://developers.google.com/appengine/docs/go/blobstore/#Uploading_a_Blob
	blobs, otherParams, err := blobstore.ParseUpload(r)
	if err != nil {
		return "", nil, err
	}
	file := blobs[name]
	if len(file) == 0 {
		return "", otherParams, nil
	}
	return string(file[0].BlobKey), otherParams, nil
}
func (a *GaeDatastoreAccessor) processUploadFiles(r *http.Request, names []string) ([]string, map[string][]string, error) {
	blobs, otherParams, err := blobstore.ParseUpload(r)
	if err != nil {
		return nil, nil, err
	}
	blobKeys := []string{}
	for _, name := range names {
		if file := blobs[name]; len(file) > 0 {
			blobKeys = append(blobKeys, string(file[0].BlobKey))
		}
	}
	return blobKeys, otherParams, nil
}
Пример #3
0
func handleUpload(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		serveError(ctx, w, err)
		return
	}
	file := blobs["file"]
	if len(file) == 0 {
		log.Errorf(ctx, "no file uploaded")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
}
Пример #4
0
func addHandler(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseGlob("template/*")) // add sub-templates in /template
	if r.Method == "GET" {                               // get method display form
		t.ParseFiles("add.html")                                // parse add.html if 'method' = 'get'
		ctx := appengine.NewContext(r)                          // get ctx
		uploadURL, err := blobstore.UploadURL(ctx, "/add", nil) // get uploadurl for blobstore
		if err != nil {
			return
		}
		actionURL := map[string]string{"BlobActionURL": uploadURL.String()} // provide blobuploadurl to action field of the form
		t.ExecuteTemplate(w, "base", actionURL)
	}
	if r.Method == "POST" {
		ctx := appengine.NewContext(r)
		r.ParseForm()
		blobs, others, err := blobstore.ParseUpload(r) // get upload blob info
		if err != nil {
			w.Write([]byte(err.Error())) // error
			return
		}
		files := blobs["img"]                    // name="img" in the html form
		title := others.Get("title")             // '' title
		password := others.Get("password")       // '' password
		description := others.Get("description") // '' description

		var blobKeys []string
		var imgSrcs []string
		for _, file := range files {
			imgSrc := "/serve/?blobKey=" + string(file.BlobKey) // create imgsrc url from blobkey
			imgSrcs = append(imgSrcs, imgSrc)                   //multiple images in singe post
			blobKeys = append(blobKeys, string(file.BlobKey))   // also save blobkey in case for use.
		}

		var post m.Post // creating post and fill the fields.
		post.Title = title
		post.Password = password
		post.Description = description
		post.BlobKeys = blobKeys
		post.Time = time.Now()
		post.ImageSrc = imgSrcs

		posts := []m.DataModel{post}            // uploading posts
		keys, _ := m.SaveDataModels(ctx, posts) // success?
		i := strconv.Itoa(int(keys[0].IntID()))
		http.Redirect(w, r, "/main/?id="+i, http.StatusFound) // redirect to /main/?uuid= with uuid
		// http.Redirect(w, r, "/error", http.StatusNotFound)
	}
}
Пример #5
0
func Upload(c *gin.Context) {
	r := c.Request
	ctx := appengine.NewContext(r)
	var err_msg string

	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		log.Errorf(ctx, err.Error())
		err_msg = err.Error()
	}
	file := blobs["file"]
	if len(file) == 0 {
		log.Errorf(ctx, "file length is 0")
		err_msg = "file length is 0"
	}
	c.JSON(http.StatusOK, gin.H{"err": err_msg, "blobKey": string(file[0].BlobKey)})
}
Пример #6
0
func sampleHandler2(w http.ResponseWriter, r *http.Request) {
	// [START uploading_a_blob_3]
	ctx := appengine.NewContext(r)
	blobs, _, err := blobstore.ParseUpload(r)
	if err != nil {
		serveError(ctx, w, err)
		return
	}
	file := blobs["file"]
	if len(file) == 0 {
		log.Errorf(ctx, "no file uploaded")
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	http.Redirect(w, r, "/serve/?blobKey="+string(file[0].BlobKey), http.StatusFound)
	// [END uploading_a_blob_3]

	// [START serving_a_blob]
	blobstore.Send(w, appengine.BlobKey(r.FormValue("blobKey")))
	// [END serving_a_blob]
}
Пример #7
0
func uploadToBlob(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	// posting image to blob, posting blobbedImage to datastore
	blobs, _, err := blobstore.ParseUpload(req) // from request, take and parse the blobs from the form.
	if err != nil {
		serveTemplateWithParams(res, req, "falure.html", "BLOB PARSE ERROR") // something went wrong with the parse
		return
	}

	file := blobs["file"] // okay. have blobs now.
	if len(file) == 0 {   // are there any files?
		serveTemplateWithParams(res, req, "falure.html", "NO BLOBS FOUND")
		return
	}

	sess, good := getSession(req) // ensure that there is a good session.
	if good != nil {
		serveTemplateWithParams(res, req, "falure.html", "LOGIN TOKEN HAS EXPIRED, CANNOT PROCESS IMAGE")
		return
	}
	var sd Session
	json.Unmarshal(sess.Value, &sd)

	blobImage := blobbedImage{ // make the blob based on what we took in.
		BlobSRC:  makeImageURL(req, string(file[0].BlobKey)),
		URL:      sd.UserName,
		UsrEmail: sd.Email,
		Uploaded: file[0].CreationTime,
	}

	ctx := appengine.NewContext(req) // prep and submit to datastore
	key := datastore.NewKey(ctx, "Images", blobImage.URL, 0, nil)
	key, err = datastore.Put(ctx, key, &blobImage)
	if err != nil {
		serveTemplateWithParams(res, req, "falure.html", "INTERNAL DATASTORE ERROR")
		return
	}

	http.Redirect(res, req, "/view/"+blobImage.URL, http.StatusFound)
	//http.Redirect(res, req, "/", 302)
}
Пример #8
0
func handleFiles(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	switch r.Method {
	case "POST":
		blobs, _, err := blobstore.ParseUpload(r)
		if err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			log.Errorf(c, "bad request: %s", err.Error())
			return
		}

		url, err := blobstore.UploadURL(c, "/admin/files", nil)
		if err == nil {
			w.Header().Set("UploadURL", url.String())
		}

		files := make([]File, 0, 20)
		for _, infos := range blobs {
			for _, info := range infos {
				var file File
				file.Name = info.Filename
				file.URL = "/blob/" + string(info.BlobKey)
				file.ID = string(info.BlobKey)
				file.Size = info.Size
				_, err = datastore.Put(c, datastore.NewKey(c, "File", file.ID, 0, nil), &file)
				if err != nil {
					log.Errorf(c, "add file to datastore '%s': %s", info.BlobKey, err.Error())
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				files = append(files, file)
			}
		}

		w.Header().Set("Content-Type", "application/json")
		err = json.NewEncoder(w).Encode(&files)
		if err != nil {
			log.Errorf(c, "json encode: %s", err.Error())
		}
	case "GET":
		var files []File
		_, err := datastore.NewQuery("File").GetAll(c, &files)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			log.Errorf(c, "query files: %s", err.Error())
			return
		}
		w.Header().Set("Content-Type", "application/json")
		if files == nil {
			files = []File{}
		}
		err = json.NewEncoder(w).Encode(&files)
		if err != nil {
			log.Errorf(c, "json encode: %s", err.Error())
		}
	default:
		http.Error(w, "Valid methods are GET and POST", http.StatusMethodNotAllowed)
		return
	}
}
Пример #9
0
func handleImages(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	switch r.Method {
	case "POST":
		blobs, vals, err := blobstore.ParseUpload(r)
		if err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			log.Errorf(c, "bad request: %s", err.Error())
			return
		}
		bucketID := vals.Get("BucketID")
		if bucketID == "" {
			http.Error(w, "BucketID query parameter is required", http.StatusBadRequest)
			return
		}
		url, err := blobstore.UploadURL(c, "/admin/images", nil)
		if err == nil {
			w.Header().Set("UploadURL", url.String())
		}
		imgs := make([]Image, 0, 20)
		for _, infos := range blobs {
			for _, info := range infos {
				var img Image
				img.Name = info.Filename
				imgUrl, err := aimage.ServingURL(c, info.BlobKey, nil)
				if err != nil {
					log.Errorf(c, "failed to get serving url for blob '%s': %s", info.BlobKey, err.Error())
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				img.URL = imgUrl.String()
				img.ID = string(info.BlobKey)
				ir := blobstore.NewReader(c, info.BlobKey)
				cfg, _, err := image.DecodeConfig(ir)
				if err != nil {
					log.Warningf(c, "decode image '%s': %s", info.BlobKey, err.Error())
					err = blobstore.Delete(c, info.BlobKey)
					if err != nil {
						log.Errorf(c, "delete blob '%s': %s", info.BlobKey, err.Error())
					}
					continue
				}
				img.Height = cfg.Height
				img.Width = cfg.Width
				imgs = append(imgs, img)
			}
		}

		// add images to bucket and dtore
		err = datastore.RunInTransaction(c, func(c context.Context) error {
			bucketKey := datastore.NewKey(c, "Bucket", bucketID, 0, nil)
			var b Bucket
			err := datastore.Get(c, bucketKey, &b)
			if err != nil {
				return err
			}
			if b.Images == nil {
				b.Images = make([]string, 0, len(imgs))
			}
			for _, img := range imgs {
				_, err = datastore.Put(c, datastore.NewKey(c, "Image", img.ID, 0, nil), &img)
				if err != nil {
					return err
				}
				b.Images = append(b.Images, img.ID)
			}
			_, err = datastore.Put(c, bucketKey, &b)
			return err
		}, &datastore.TransactionOptions{XG: true})

		if err == datastore.ErrNoSuchEntity {
			for _, img := range imgs {
				err = blobstore.Delete(c, appengine.BlobKey(img.ID))
				if err != nil {
					log.Warningf(c, "delete blob '%s': %s", img.ID, err.Error())
				}
			}
			http.NotFound(w, r)
			return
		}
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			log.Errorf(c, "update datastore: %s", err.Error())
			return
		}

		w.Header().Set("Content-Type", "application/json")
		err = json.NewEncoder(w).Encode(&imgs)
		if err != nil {
			log.Errorf(c, "json encode: %s", err.Error())
		}
	case "GET":
		var imgs []Image
		_, err := datastore.NewQuery("Image").GetAll(c, &imgs)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			log.Errorf(c, "query images: %s", err.Error())
			return
		}
		w.Header().Set("Content-Type", "application/json")
		if imgs == nil {
			imgs = []Image{}
		}
		err = json.NewEncoder(w).Encode(&imgs)
		if err != nil {
			log.Errorf(c, "json encode: %s", err.Error())
		}
	default:
		http.Error(w, "Valid methods are GET and POST", http.StatusMethodNotAllowed)
		return
	}
}