Пример #1
0
func sampleHandler(w http.ResponseWriter, r *http.Request) {
	// [START uploading_a_blob_2]
	var rootTemplate = template.Must(template.New("root").Parse(rootTemplateHTML))

	const rootTemplateHTML = `
<html><body>
<form action="{{.}}" method="POST" enctype="multipart/form-data">
Upload File: <input type="file" name="file"><br>
<input type="submit" name="submit" value="Submit">
</form></body></html>
`
	// [END uploading_a_blob_2]

	// [START uploading_a_blob_1]
	ctx := appengine.NewContext(r)
	uploadURL, err := blobstore.UploadURL(ctx, "/upload", nil)
	if err != nil {
		serveError(ctx, w, err)
		return
	}
	w.Header().Set("Content-Type", "text/html")
	err = rootTemplate.Execute(w, uploadURL)
	if err != nil {
		log.Errorf(ctx, "%v", err)
	}
	// [END uploading_a_blob_1]
}
Пример #2
0
func submitUpload(w http.ResponseWriter, r *http.Request, m map[string]interface{}) {

	c := appengine.NewContext(r)
	uploadURL, err := blobstore.UploadURL(c, "/blob2/processing-new-upload", nil)
	loghttp.E(w, r, err, false)

	w.Header().Set("Content-type", "text/html; charset=utf-8")
	err = upload2.Execute(w, uploadURL)
	loghttp.E(w, r, err, false)
}
Пример #3
0
func handleAdminPage(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	url, err := blobstore.UploadURL(c, "/admin/images", nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Errorf(c, "failed to get upload url: %s", err.Error())
		return
	}
	furl, err := blobstore.UploadURL(c, "/admin/files", nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		log.Errorf(c, "failed to get file upload url: %s", err.Error())
		return
	}

	err = t.ExecuteTemplate(w, "admin.html", struct{ UploadURL, FilesUploadURL string }{url.String(), furl.String()})
	if err != nil {
		log.Errorf(c, "render admin.html: %s", err.Error())
	}
}
Пример #4
0
func handleRoot(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	uploadURL, err := blobstore.UploadURL(ctx, "/upload", nil)
	if err != nil {
		serveError(ctx, w, err)
		return
	}
	w.Header().Set("Content-Type", "text/html")
	err = rootTemplate.Execute(w, uploadURL)
	if err != nil {
		log.Errorf(ctx, "%v", err)
	}
}
Пример #5
0
func UploadUrl(c *gin.Context) {
	r := c.Request
	ctx := appengine.NewContext(r)
	uploadURL, err := blobstore.UploadURL(ctx, "/admin/upload", nil)
	var err_msg string

	if err != nil {
		log.Errorf(ctx, err.Error())
		err_msg = err.Error()
	}

	c.JSON(http.StatusOK, gin.H{"err": err_msg, "uploadOPT": uploadURL, "uploadURL": uploadURL.String()})

}
Пример #6
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)
	}
}
Пример #7
0
func uploadForm(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	// serving image upload form
	ctx := appengine.NewContext(req)
	uploadURL, err := blobstore.UploadURL(ctx, "/upload", nil) // setting up the post call for blobstore.
	if err != nil {
		serveTemplateWithParams(res, req, "falure.html", "BLOB URL ERROR") // there was an issue making the post call
		return
	}

	_, err = getSession(req)
	if err != nil {
		serveTemplateWithParams(res, req, "falure.html", "YOU MAY NOT SUBMIT FILES WITHOUT BEING LOGGED IN") // there was an issue making the post call
		return
	}

	serveTemplateWithParams(res, req, "upload.html", uploadURL)
}
Пример #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
	}
}