//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 }
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) }
// 画像のアップロード 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)) }
// 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 }
// 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 }
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) }
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") }
/* * 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 }
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 }
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) }
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 }
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) }
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 }
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) }
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) }
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 }
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)) }
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 }
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) }
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 }
func submit(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) blobs, other, err := blobstore.ParseUpload(r) if err != nil { w.WriteHeader(http.StatusInternalServerError) w.Header().Set("Content-type", "text/plain") io.WriteString(w, "Internal Server Error") c.Errorf("%v", err) return } members := regexp.MustCompile(",").Split(string(other["inputGroup"][0]), -1) editors := regexp.MustCompile(",").Split(string(other["inputEditors"][0]), -1) var now Period datastore.Get(c, currentSemesterKey(c), &now) log.Println(now) count, cnterr := datastore.NewQuery("Tile").Ancestor(tileRootKey(c, now.Semester, now.Year)).Filter("Name =", string(other["inputName"][0])).Count(c) if cnterr != nil { log.Println("Something failed with counting for some reason") } newdata := Tile{ Name: string(other["inputName"][0]), Number: count, Desc: string(other["textArea"][0]), Category: string(other["inputCategory"][0]), Imgref: string(blobs["inputFile"][0].BlobKey), Members: members, Creator: user.Current(c).String(), CanEdit: editors, LastUpdate: time.Now(), UpdatedBy: string(user.Current(c).String()), Period: now, } log.Println(newdata) key := datastore.NewKey(c, "Tile", strint(newdata.Name, count), 0, tileRootKey(c, now.Semester, now.Year)) _, keyerr := datastore.Put(c, key, &newdata) if keyerr != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // log.Println(w.Header) http.Redirect(w, r, "/", http.StatusFound) }
func (fileStore *blobstoreFileStore) GetUploadedFileKey(r *http.Request, name string) (err error, key string) { var blobs map[string][]*blobstore.BlobInfo blobs, _, err = blobstore.ParseUpload(r) if err != nil { key = "" return } file := blobs[name] if len(file) == 0 { err = errors.New("No file uploaded") key = "" return } key = string(file[0].BlobKey) err = nil return }
func handleUpload(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) blobs, other, err := blobstore.ParseUpload(r) if err != nil { serveError(c, w, err) return } mainPhoto := blobs["mainPhoto"][0].BlobKey creationTime := blobs["mainPhoto"][0].CreationTime result := ResultData{ Manufacturer: other["manufacturer"][0], MainPhoto: mainPhoto, CreationTime: creationTime, } key, err := datastore.Put(c, datastore.NewIncompleteKey(c, "lighting", nil), &result) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } var result2 ResultData if err = datastore.Get(c, key, &result2); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html") url, err := image.ServingURL(c, result2.MainPhoto, nil) if err != nil { serveError(c, w, err) return } toPass := &ResultRead2{result2, template.HTML(url.String())} w.Header().Set("Content-Type", "text/html") err = uploadTemplate.Execute(w, toPass) if err != nil { serveError(c, w, err) return } }
func handleUpload(ctx *Context, w http.ResponseWriter, r *http.Request) error { if ctx.user == nil { return fmt.Errorf("User cannot be nil!") } blobs, fields, err := blobstore.ParseUpload(ctx.r) if err != nil { return err } //vendor := getFormFieldString(fields, "vendor") amt := getFormFieldInt(fields, "amount") file := blobs["file"] if len(file) == 0 { ctx.c.Errorf("no file uploaded") http.Redirect(w, r, "/", http.StatusFound) return nil } b := Bill{ Amt: amt, PostedOn: time.Now(), PostedBy: ctx.user.String(), BlobKey: file[0].BlobKey, } key := datastore.NewIncompleteKey(ctx.c, "Bill", nil) billKey, err := datastore.Put(ctx.c, key, &b) if err != nil { return err } http.Redirect(w, r, "/view/?id="+billKey.Encode(), http.StatusFound) return nil }
func upload(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) c.Debugf("10") blobs, _, err := blobstore.ParseUpload(r) if err != nil { c.Errorf("parse upload failed.") http.Error(w, err.String(), http.StatusInternalServerError) return } else { c.Debugf("parse upload successful!") } file := blobs["file"] if len(file) == 0 { c.Errorf("no file uploaded") http.Redirect(w, r, "/", http.StatusFound) return } else { c.Debugf("find file uploaded.") } http.Redirect(w, r, "/store?blobKey="+string(file[0].BlobKey), http.StatusFound) }
func Restore(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) blobs, _, err := blobstore.ParseUpload(r) if err != nil { c.Errorf("%v", err) return } file := blobs["file"] if len(file) == 0 { c.Errorf("no file uploaded") http.Redirect(w, r, "/", http.StatusFound) return } blobKey := file[0].BlobKey key := string(blobKey) t := taskqueue.NewPOSTTask("/restoreTask", map[string][]string{"blobKey": {key}}) _, err = taskqueue.Add(c, t, "") if err != nil { c.Errorf("Could not add task. Error was: %v", err) return } http.Redirect(w, r, "/", http.StatusFound) }
func fileUploadProcess(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 { http.Redirect(w, r, "/file?action=upload", http.StatusFound) return } // New FileData fileData := FileData{Success: true, BlobKey: string(file[0].BlobKey)} // New PageSetting pageSetting := new(PageSetting) // Setting pageSetting pageSetting.Title = "File Upload - " + config.Title pageSetting.Layout = "column1" pageSetting.ShowSidebar = false // New PageData pageData := &PageData{File: fileData} // New Page page := NewPage(pageSetting, pageData) // Render page page.Render("file/upload", w) }
func Save(blog_config map[string]interface{}) func(w http.ResponseWriter, req *http.Request) { l := func(w http.ResponseWriter, req *http.Request) { appcontext := appengine.NewContext(req) blobs, _, err := blobstore.ParseUpload(req) if err != nil { appcontext.Errorf("error parsing blobstore! %v", err) http.Error(w, "error parsing blobstore!", http.StatusBadRequest) return } //key := "coolguys" key := req.FormValue("g") if key == "" { http.Error(w, "did not specify a key!", http.StatusBadRequest) return } send_message := func(stat string, color string) { con := map[string]interface{}{"status": stat, "color": color} err := channel.SendJSON(appcontext, key, con) if err != nil { appcontext.Errorf("sending update message: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) } } bdata, ok := blobs["data"] if !ok { http.Error(w, "did not specify data as a param", http.StatusBadRequest) send_message("internal error while saving!", "#AA0000") return } if len(bdata) != 1 { appcontext.Errorf("error parsing blobstore!", err) http.Error(w, "error parsing blobstore!", http.StatusBadRequest) return } jsonkey := bdata[0].BlobKey data, err := ioutil.ReadAll(blobstore.NewReader(appcontext, jsonkey)) if err != nil { appcontext.Errorf("error parsing blobstore!", err) http.Error(w, "error parsing blobstore!", http.StatusBadRequest) return } if len(data) <= 0 { http.Error(w, "did not specify data as a param", http.StatusBadRequest) send_message("internal error while saving!", "#AA0000") return } var decoded interface{} err = json.Unmarshal(data, &decoded) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) send_message("internal error while saving!", "#AA0000") return } q := decoded.(map[string]interface{}) _, ok = q["data"].(string) if !ok { http.Error(w, "error: must supply JSON with 'data' specified!", http.StatusBadRequest) send_message("internal error while saving!", "#AA0000") return } title, ok := q["title"].(string) if !ok { http.Error(w, "error: must supply JSON with 'title' specified!", http.StatusBadRequest) send_message("internal error while saving!", "#AA0000") return } labels, ok := q["labels"].(string) if !ok { http.Error(w, "error: must supply JSON with 'labels' specified!", http.StatusBadRequest) send_message("internal error while saving!", "#AA0000") return } individual_labels := strings.Split(labels, ",") real_labels := make([]string, len(individual_labels)) for i := range individual_labels { real_labels[i] = strings.ToLower(strings.Trim(individual_labels[i], " \t")) } _, err = post.SavePost(appcontext, title, jsonkey, real_labels, time.Now()) if err != nil { appcontext.Errorf("saving a post: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) send_message("internal error while saving!", "#AA0000") return } send_message("saved", "#00AA00") } return l }
func ImportOpml(c mpg.Context, w http.ResponseWriter, r *http.Request) { cu := user.Current(c) gn := goon.FromContext(c) u := User{Id: cu.ID} if err := gn.Get(&u); err != nil { serveError(w, err) return } backupOPML(c) blobs, _, err := blobstore.ParseUpload(r) if err != nil { serveError(w, err) return } fs := blobs["file"] if len(fs) == 0 { serveError(w, fmt.Errorf("no uploaded file found")) return } file := fs[0] fr := blobstore.NewReader(c, file.BlobKey) del := func() { blobstore.Delete(c, file.BlobKey) } fdata, err := ioutil.ReadAll(fr) if err != nil { del() serveError(w, err) return } buf := bytes.NewReader(fdata) // attempt to extract from google reader takeout zip if zb, zerr := zip.NewReader(buf, int64(len(fdata))); zerr == nil { for _, f := range zb.File { if strings.HasSuffix(f.FileHeader.Name, "Reader/subscriptions.xml") { if rc, rerr := f.Open(); rerr == nil { if fb, ferr := ioutil.ReadAll(rc); ferr == nil { fdata = fb break } } } } } // Preflight the OPML, so we can report any errors. d := xml.NewDecoder(bytes.NewReader(fdata)) d.CharsetReader = charset.NewReader d.Strict = false opml := Opml{} if err := d.Decode(&opml); err != nil { del() serveError(w, err) c.Errorf("opml error: %v", err.Error()) return } task := taskqueue.NewPOSTTask(routeUrl("import-opml-task"), url.Values{ "key": {string(file.BlobKey)}, "user": {cu.ID}, }) taskqueue.Add(c, task, "import-reader") }
// Handles the Uploads func handleUpload(w http.ResponseWriter, r *http.Request) { blobstore.ParseUpload(r) http.Redirect(w, r, "/admin/files/", http.StatusFound) }