Esempio n. 1
5
func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	oa := CheckAuthorized(w, r, false)
	if oa == nil {
		return
	}
	if r.Method != "POST" {
		http.Redirect(w, r, "/", http.StatusFound)
		return
	}
	m, _, err := r.FormFile("server")
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	defer m.Close()
	dst, err := os.Create(deployFileName)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	_, err = io.Copy(dst, m)
	dst.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	finfo, _ := os.Stat(deployFileName)

	w.WriteHeader(200)
	w.Write([]byte("Uploaded: " + humanize.Bytes(uint64(finfo.Size()))))

}
Esempio n. 2
1
func handlePut(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	hc := &http.Client{
		Transport: &oauth2.Transport{
			Source: google.AppEngineTokenSource(ctx, storage.ScopeFullControl),
			Base:   &urlfetch.Transport{Context: ctx},
		},
	}

	cctx := cloud.NewContext(appengine.AppID(ctx), hc)

	rdr, hdr, err := req.FormFile("form-upload-file")
	if err != nil {
		http.Error(res, "ERROR RECEIVING FILE: "+err.Error(), 500)
		return
	}

	writer := storage.NewWriter(cctx, bucketName, hdr.Filename)
	io.Copy(writer, rdr)

	err = writer.Close()
	if err != nil {
		http.Error(res, "ERROR WRITING TO BUCKET: "+err.Error(), 500)
		return
	}
}
Esempio n. 3
0
func BuildCreate(rw http.ResponseWriter, r *http.Request) *httperr.Error {
	vars := mux.Vars(r)
	app := vars["app"]

	cache := !(r.FormValue("cache") == "false")
	manifest := r.FormValue("manifest")
	description := r.FormValue("description")

	repo := r.FormValue("repo")
	index := r.FormValue("index")

	source, _, err := r.FormFile("source")
	if err != nil && err != http.ErrMissingFile && err != http.ErrNotMultipart {
		helpers.TrackError("build", err, map[string]interface{}{"at": "FormFile"})
		return httperr.Server(err)
	}

	// Log into private registries that we might pull from
	// TODO: move to prodiver BuildCreate
	err = models.LoginPrivateRegistries()
	if err != nil {
		return httperr.Server(err)
	}

	a, err := models.GetApp(app)
	if err != nil {
		return httperr.Server(err)
	}

	// Log into registry that we will push to
	_, err = models.AppDockerLogin(*a)
	if err != nil {
		return httperr.Server(err)
	}

	var b *structs.Build

	// if source file was posted, build from tar
	if source != nil {
		b, err = models.Provider().BuildCreateTar(app, source, r.FormValue("manifest"), r.FormValue("description"), cache)
	} else if repo != "" {
		b, err = models.Provider().BuildCreateRepo(app, repo, r.FormValue("manifest"), r.FormValue("description"), cache)
	} else if index != "" {
		var i structs.Index
		err := json.Unmarshal([]byte(index), &i)
		if err != nil {
			return httperr.Server(err)
		}

		b, err = models.Provider().BuildCreateIndex(app, i, manifest, description, cache)
	} else {
		return httperr.Errorf(403, "no source, repo or index")
	}

	if err != nil {
		return httperr.Server(err)
	}

	return RenderJson(rw, b)
}
Esempio n. 4
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("files")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer file.Close()

	f, err := os.OpenFile("./uploads/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer f.Close()
	io.Copy(f, file)

	files := Files{
		File{Name: handler.Filename, Type: handler.Header["Content-Type"][0]},
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(files); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

}
Esempio n. 5
0
// hello world, the web server
func HelloServer(w http.ResponseWriter, r *http.Request) {
	if "POST" == r.Method {
		file, _, err := r.FormFile("userfile")
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}

		if statInterface, ok := file.(Stat); ok {
			fileInfo, _ := statInterface.Stat()
			fmt.Fprintf(w, "上传文件的大小为: %d", fileInfo.Size())
		}
		if sizeInterface, ok := file.(Size); ok {
			fmt.Fprintf(w, "上传文件的大小为: %d", sizeInterface.Size())
		}

		return
	}

	// 上传页面
	w.Header().Add("Content-Type", "text/html")
	w.WriteHeader(200)
	html := `
<form enctype="multipart/form-data" action="/hello" method="POST">
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
`
	io.WriteString(w, html)
}
Esempio n. 6
0
// uploadFileFromForm uploads a file if it's present in the "image" form field.
func uploadFileFromForm(r *http.Request) (url string, err error) {
	f, fh, err := r.FormFile("image")
	if err == http.ErrMissingFile {
		return "", nil
	}
	if err != nil {
		return "", err
	}

	if bookshelf.StorageBucket == nil {
		return "", errors.New("storage bucket is missing - check config.go")
	}

	// random filename, retaining existing extension.
	name := uuid.NewV4().String() + path.Ext(fh.Filename)

	ctx := context.Background()
	w := bookshelf.StorageBucket.Object(name).NewWriter(ctx)
	w.ACL = []storage.ACLRule{{storage.AllUsers, storage.RoleReader}}
	w.ContentType = fh.Header.Get("Content-Type")

	// Entries are immutable, be aggressive about caching (1 day).
	w.CacheControl = "public, max-age=86400"

	if _, err := io.Copy(w, f); err != nil {
		return "", err
	}
	if err := w.Close(); err != nil {
		return "", err
	}

	const publicURL = "https://storage.googleapis.com/%s/%s"
	return fmt.Sprintf(publicURL, bookshelf.StorageBucketName, name), nil
}
Esempio n. 7
0
func (api *API) ServeV1WriteNQuad(w http.ResponseWriter, r *http.Request, params httprouter.Params) int {
	if api.config.ReadOnly {
		return jsonResponse(w, 400, "Database is read-only.")
	}

	formFile, _, err := r.FormFile("NQuadFile")
	if err != nil {
		glog.Errorln(err)
		return jsonResponse(w, 500, "Couldn't read file: "+err.Error())
	}
	defer formFile.Close()

	blockSize, blockErr := strconv.ParseInt(r.URL.Query().Get("block_size"), 10, 64)
	if blockErr != nil {
		blockSize = int64(api.config.LoadSize)
	}

	quadReader, err := internal.Decompressor(formFile)
	// TODO(kortschak) Make this configurable from the web UI.
	dec := cquads.NewDecoder(quadReader)

	h, err := api.GetHandleForRequest(r)
	if err != nil {
		return jsonResponse(w, 400, err)
	}

	n, err := quad.CopyBatch(h, dec, int(blockSize))
	if err != nil {
		return jsonResponse(w, 400, err)
	}
	fmt.Fprintf(w, "{\"result\": \"Successfully wrote %d quads.\"}", n)

	return 200
}
Esempio n. 8
0
// Handles uploadTextFile page using a template.
func uploadTextFile(res http.ResponseWriter, req *http.Request) {

	temp, err := template.ParseFiles("./uploadTextFile.html")
	// Logging possible errors
	logError(err)

	if req.Method == "POST" {

		inFile, _, err := req.FormFile("file")
		defer inFile.Close()
		// Logging possible errors
		logError(err)

		contents, err := ioutil.ReadAll(inFile)
		// Logging possible errors
		logError(err)

		err = temp.Execute(res, string(contents))
	} else {
		err = temp.Execute(res, false)
	}
	// Logging possible errors
	logError(err)

}
Esempio n. 9
0
func GenPage(res http.ResponseWriter, req *http.Request) {
	fmt.Fprint(res, `<!DOCTYPE html>
					<html>
					<body>
						<form method = "POST"  enctype="multipart/form-data">
							<input type="file" name="inputField"><br>
							<input type ="submit">
						</form>
					</body>
					</html>`)

	if req.Method == "POST" {
		key := "name"
		_, hdr, err := req.FormFile(key)
		if err != nil {
			fmt.Println(err)
		}

		rdr, err2 := hdr.Open()
		if err2 != nil {
			fmt.Println(err2)
		}

		io.Copy(res, rdr)
	}

	tpl.Execute(res, nil)
	hdr, _ := ioutil.ReadFile("file.txt")
	fmt.Fprint(res, strings.Split(string(hdr), "\n"))
}
Esempio n. 10
0
func doConvert(l *log.Logger, w http.ResponseWriter, r *http.Request) error {
	in, _, e := r.FormFile("input")
	if e != nil {
		return e
	}
	data, e := ioutil.ReadAll(in)
	in.Close()
	if e != nil {
		return e
	}

	folder, e := NewZipFolder(data)
	if e != nil {
		return e
	}

	maker := NewEpubMaker(l)
	if e = maker.Process(folder, r.FormValue("duokan") == "duokan"); e != nil {
		return e
	}

	ver := EPUB_VERSION_300
	if r.FormValue("epub2") == "epub2" {
		ver = EPUB_VERSION_200
	}
	if data, name, e := maker.GetResult(ver); e != nil {
		return e
	} else {
		w.Header().Add("Content-Disposition", "attachment; filename="+name)
		http.ServeContent(w, r, name, time.Now(), bytes.NewReader(data))
	}

	return nil
}
Esempio n. 11
0
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls
func (o *UploadFileParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
	var res []error
	if err := r.ParseMultipartForm(32 << 20); err != nil {
		return err
	}
	fds := httpkit.Values(r.Form)

	fdAdditionalMetadata, fdhkAdditionalMetadata, _ := fds.GetOK("additionalMetadata")
	if err := o.bindAdditionalMetadata(fdAdditionalMetadata, fdhkAdditionalMetadata, route.Formats); err != nil {
		res = append(res, err)
	}

	file, fileHeader, err := r.FormFile("file")
	if err != nil {
		res = append(res, errors.New(400, "reading file %q failed: %v", "file", err))
	} else {
		o.File = httpkit.File{Data: file, Header: fileHeader}
	}

	rPetID, rhkPetID, _ := route.Params.GetOK("petId")
	if err := o.bindPetID(rPetID, rhkPetID, route.Formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
Esempio n. 12
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	id, err := sessionHandling(w, r)
	if err != nil {
		log.Printf("error in session handling (%v)", err)
		fmt.Fprintf(w, "Error: %v", err)
		return
	}
	file, header, err := r.FormFile("file")
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}
	defer file.Close()
	out, err := os.Create(*uploadDir + "/" + header.Filename)
	if err != nil {
		log.Printf("Unable to create the file %v for writing. Check your write access privilege (session: %v, error: %v)", *uploadDir+"/"+header.Filename, id, err)
		fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
		return
	}
	defer out.Close()
	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Fprintln(w, err)
	}
	log.Printf("successfully accepted file %v from session %v", *uploadDir+"/"+header.Filename, id)
	fmt.Fprintf(w, "File uploaded successfully : ")
	fmt.Fprintf(w, header.Filename)
}
Esempio n. 13
0
func index(res http.ResponseWriter, req *http.Request) {
	ctx := appengine.NewContext(req)

	id, err := getID(res, req)
	if err != nil {
		log.Errorf(ctx, "getID: %s", err)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	if req.Method == "POST" {
		src, _, err := req.FormFile("data")
		if err != nil {
			log.Errorf(ctx, "ERROR index req.FormFile: %s", err)
			http.Redirect(res, req, `/?id=`+id, http.StatusSeeOther)
			return
		}
		err = uploadPhoto(src, id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index uploadPhoto: %s", err)
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
	}

	m, err := retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
		http.Redirect(res, req, "/logout", http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "index.html", m)
}
Esempio n. 14
0
////////////////////////////////
// Upload files
////////////////////////////////
func uploads(w http.ResponseWriter, r *http.Request) {
	type file struct {
		Name string
	}

	if r.Method == "GET" {
		filez, _ := ioutil.ReadDir("./uploads/")
		files := []file{}
		for _, fn := range filez {
			f := file{}
			f.Name = fn.Name()
			files = append(files, f)
		}
		t.ExecuteTemplate(w, "header", v)
		t.ExecuteTemplate(w, "upload", files)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		f, err := os.OpenFile("./uploads/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
		http.Redirect(w, r, "/kayden/upload", 302)
	}
}
Esempio n. 15
0
// Paste receives a new paste from a client.
func Paste(resp http.ResponseWriter, req *http.Request) {
	go logRequest(req)
	req.ParseForm()
	var contents []byte
	key := ChooseKey()
	if data := req.Form.Get("content"); len(data) > 0 {
		contents = []byte(data)
		logger.Printf("new paste: inline %s %v (%d bytes)",
			key, [3]uint16(key), len(contents))
	} else {
		file, hdr, er := req.FormFile("file")
		if er == nil {
			truncfile := io.LimitReader(file, 512<<10)
			contents, er = ioutil.ReadAll(truncfile)
		}
		if er != nil {
			sendError(resp, er)
			return
		}
		name := hdr.Filename
		mime := hdr.Header.Get("Content-Type")
		logger.Printf("new paste: %s %s %s %v (%d bytes)",
			name, mime, key, [3]uint16(key), len(contents))
	}
	allPastes[key] = Item(contents)
	fmt.Fprintf(resp, "http://%s/pastehere/view/%s", req.Host, key)
}
Esempio n. 16
0
func platformUpdate(w http.ResponseWriter, r *http.Request, t auth.Token) error {
	defer r.Body.Close()
	name := r.URL.Query().Get(":name")
	file, _, _ := r.FormFile("dockerfile_content")
	if file != nil {
		defer file.Close()
	}
	args := make(map[string]string)
	for key, values := range r.Form {
		args[key] = values[0]
	}
	canUpdatePlatform := permission.Check(t, permission.PermPlatformUpdate)
	if !canUpdatePlatform {
		return permission.ErrUnauthorized
	}
	w.Header().Set("Content-Type", "text")
	keepAliveWriter := io.NewKeepAliveWriter(w, 30*time.Second, "")
	defer keepAliveWriter.Stop()
	writer := &io.SimpleJsonMessageEncoderWriter{Encoder: json.NewEncoder(keepAliveWriter)}
	err := app.PlatformUpdate(provision.PlatformOptions{
		Name:   name,
		Args:   args,
		Input:  file,
		Output: writer,
	})
	if err != nil {
		writer.Encode(io.SimpleJsonMessage{Error: err.Error()})
		writer.Write([]byte("Failed to update platform!\n"))
		return nil
	}
	writer.Write([]byte("Platform successfully updated!\n"))
	return nil
}
Esempio n. 17
0
func uploadfunc(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.Write([]byte("hello world from host1" + r.Method + "\n"))
		return
	}
	r.ParseMultipartForm(1 << 20)
	//w.Write([]byte("hello world from host1"))
	//w.Write([]byte(r.Header.Get("Content-Type")))
	f, fh, err := r.FormFile("upload")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	filename := fh.Filename
	if strings.Contains(fh.Filename, ":") {
		strtmp := strings.Split(fh.Filename, ":")
		filename = strtmp[len(strtmp)-1]
		fmt.Fprintf(w, "\nchange file name:%s\n", filename)
	} else if strings.Contains(fh.Filename, "/") {
		strtmp := strings.Split(fh.Filename, "/")
		filename = strtmp[len(strtmp)-1]
		fmt.Fprintf(w, "\nchange file name:%s\n", filename)
	}
	fmt.Fprintf(w, "\n%+v\n%s\n", fh.Header, filename)
	file, err := os.OpenFile("/tmp/"+filename, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	io.Copy(file, f)
}
Esempio n. 18
0
func upload(w http.ResponseWriter, r *http.Request) {
	log.Printf("upload request from %q\n", r.RemoteAddr)

	var err error
	defer func() {
		if err != nil {
			log.Printf("%s: %s\n", r.RemoteAddr, err)
			fmt.Fprintln(w, err)
		}
	}()

	f, h, err := r.FormFile("file")
	if err != nil {
		return
	}
	defer f.Close()

	o, err := os.Create(filepath.Join(*udir, path.Base(h.Filename)))
	if err != nil {
		return
	}

	_, err = io.Copy(o, f)
	if err != nil {
		return
	}

	err = o.Close()
	if err != nil {
		return
	}

	log.Printf("%s: upload request %q completed", r.RemoteAddr, h.Filename)
	fmt.Fprintf(w, "File uploaded successfully: %s", h.Filename)
}
Esempio n. 19
0
func handleGPXAdd(res http.ResponseWriter, r *http.Request) {
	usr, ok := users.Users[r.FormValue("user")]
	if !ok {
		http.Error(res, "User not found.", http.StatusNotFound)
		return
	}

	if r.FormValue("token") != usr.Token {
		http.Error(res, "Invalid token.", http.StatusForbidden)
		return
	}

	file, _, err := r.FormFile("gpxfile")
	if err != nil {
		http.Error(res, "Unable to read GPX file", http.StatusBadRequest)
		return
	}

	g, err := parseGPXInput(file)
	if err != nil {
		http.Error(res, fmt.Sprintf("Unable to parse GPX file: %s", err), http.StatusInternalServerError)
		return
	}
	err = addPositionsToMonthArchives(usr.Name, extractPositionsFromGPX(g))
	if err != nil {
		http.Error(res, fmt.Sprintf("Unable to save GPX positions: %s", err), http.StatusInternalServerError)
		return
	}

	http.Error(res, "OK", http.StatusOK)
}
Esempio n. 20
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("upload")
	// the FormFile function takes in the POST input id file
	file, header, err := r.FormFile("file")

	if err != nil {
		fmt.Println(err)
		return
	}

	defer file.Close()

	out, err := os.Create(*folderPtr + header.Filename)
	if err != nil {
		fmt.Println("Unable to create the file for writing. Check your write access privilege")
		return
	}

	defer out.Close()

	// write the content from POST to the file
	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Print("File uploaded successfully : ")
	fmt.Println(header.Filename)
}
Esempio n. 21
0
// function that handles the website's back end
func thisLittleWebpage(res http.ResponseWriter, req *http.Request) {
	// for simplicity, the webpage is generated here
	page := `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
        <form method = "POST" enctype="multipart/form-data"> Input your name:
          <input type="file" name="name"><br>
          <input type="submit">
        </form>
      </body>
    </html>`

	io.WriteString(res, page) // write the page

	if req.Method == "POST" {
		_, src, err := req.FormFile("name")
		if err != nil {
			fmt.Println(err)
		}

		dst, err := src.Open()
		if err != nil {
			fmt.Println(err)
		}

		io.Copy(res, dst)
	}
}
Esempio n. 22
0
// receiveHandler accepts the file and saves it to the current working directory
func receiveHandler(w http.ResponseWriter, r *http.Request) error {

	// the FormFile function takes in the POST input id file
	file, header, err := r.FormFile("file")
	if err != nil {
		fmt.Fprintln(w, err)
		return err
	}

	defer file.Close()

	out, err := os.Create(header.Filename)
	if err != nil {
		fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
		return err
	}

	defer out.Close()

	// write the content from POST to the file
	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Fprintln(w, err)
		return err
	}

	log.Println("File received:", header.Filename)

	fmt.Fprintf(w, `<html>
File uploaded successfully: %s 
<p><a href="/">Back</a></p>
<html>`, header.Filename)
	return nil
}
Esempio n. 23
0
func PostPhoto(w http.ResponseWriter, r *http.Request) {
	// the FormFile function takes in the POST input id file
	file, header, _ := r.FormFile("file")
	bits := strings.Split(header.Filename, ".")
	fileExt := bits[len(bits)-1]
	fileName := strconv.Itoa(int(time.Now().Unix())) + "." + fileExt

	uploadResult := s3s.Upload(file, fileName)

	if !uploadResult {
		log.Fatalln("Failed to upload")
	} else {
		log.Println("Uploaded")
	}

	// Get user
	u := repository.GetUserByToken(r.FormValue("token"))

	url := "http://" + os.Getenv("BUCKET") + ".s3-website-" + os.Getenv("AWS_REGION") + ".amazonaws.com/" + fileName

	// Save photo
	photo := models.Photo{
		Url:       url,
		CreatedAt: time.Now(),
		UserId:    u.Id,
		User:      u,
	}

	repository.CreatePhoto(&photo)
	json.NewEncoder(w).Encode(photo)
}
Esempio n. 24
0
func saveImgHandler(w http.ResponseWriter, r *http.Request) {
	// the FormFile function takes in the POST input id file
	file, header, err := r.FormFile("file")

	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	defer file.Close()

	filename := header.Filename

	out, err := os.Create("uploads/" + filename)
	if err != nil {
		fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege - "+
			err.Error())
		return
	}

	defer out.Close()

	// write the content from POST to the file
	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Fprintln(w, err)
	}

	fmt.Fprintf(w, "File uploaded successfully : ")
	fmt.Fprintf(w, header.Filename)
}
Esempio n. 25
0
func index(res http.ResponseWriter, req *http.Request) {

	ctx := appengine.NewContext(req)

	id := getID(res, req)

	if req.Method == "POST" {
		src, _, err := req.FormFile("data")
		if err != nil {
			log.Errorf(ctx, "ERROR index req.FormFile: %s", err)
			// TODO: create error page to show user
			http.Redirect(res, req, "/", http.StatusSeeOther)
			return
		}
		err = uploadPhoto(src, id, req)
		if err != nil {
			log.Errorf(ctx, "ERROR index uploadPhoto: %s", err)
			// expired cookie may exist on client
			http.Redirect(res, req, "/logout", http.StatusSeeOther)
			return
		}
	}

	m, err := retrieveMemc(id, req)
	if err != nil {
		log.Errorf(ctx, "ERROR index retrieveMemc: %s", err)
		// expired cookie may exist on client
		http.Redirect(res, req, "/logout", http.StatusSeeOther)
		return
	}
	tpl.ExecuteTemplate(res, "index.html", m)
}
Esempio n. 26
0
func HandleUploadCreate(w http.ResponseWriter, r *http.Request) {
	f, h, err := r.FormFile("file")
	if err != nil {
		log.Println("Error reading HttpRequest")
		ServeBadRequest(w, r)
		return
	}

	b := bytes.Buffer{}
	n, err := io.Copy(&b, io.LimitReader(f, data.MaxUploadContentSize+10))
	if err != nil {
		log.Println("Error receiving file")
		ServeInternalServerError(w, r)
		return
	}
	if n > data.MaxUploadContentSize {
		log.Println("Max Upload Content Size exceeded")
		ServeBadRequest(w, r)
		return
	}

	id := bson.NewObjectId()
	upl := data.Upload{
		ID:   id,
		Kind: data.Image,
		Content: data.Blob{
			Path: "/uploads/" + id.Hex(),
			Size: n,
		},
	}

	err = data.Bucket.Put(upl.Content.Path, b.Bytes(), h.Header.Get("Content-Type"), s3.Private, s3.Options{})
	if err != nil {
		log.Println("Error storing file to s3: ", err.Error())
		ServeInternalServerError(w, r)
		return
	}

	err = upl.Put()
	if err != nil {
		log.Println("Error storing data in Mongo")
		ServeInternalServerError(w, r)
		return
	}

	res := Upload{
		ID:      upl.ID.Hex(),
		ShortID: upl.ShortID,
		Content: UploadContent{
			URL: upl.Content.SignedURL(),
		},
	}
	w.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w).Encode(res)
	if err != nil {
		log.Println("Error Serializing response")
		ServeInternalServerError(w, r)
		return
	}
}
Esempio n. 27
0
func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		curtime := time.Now().Unix()
		h := md5.New()
		io.WriterString(h, strconv.FormatInt(curtime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))
		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f.file)
	}
}
Esempio n. 28
0
func SaveFormFileToTmp(r *http.Request, key string) (string, string, error) {
	// Parse the form.
	if err := r.ParseMultipartForm(MaxMemory); err != nil {
		return "", "", err
	}

	// Create a temporary directory.
	tempDir, err := ioutil.TempDir("", "upload-")
	if err != nil {
		log.Err(err, "When creating a temporary directory")
		return "", "", err
	}

	src, header, err := r.FormFile(key)
	if err != nil {
		return tempDir, "", err
	}

	path := filepath.Join(tempDir, header.Filename)
	dst, err := os.Create(path)
	defer dst.Close()

	if err != nil {
		log.Err(err, "When creating output file: %v", path)
	}

	// Copy the file.
	if _, err = io.Copy(dst, src); err != nil {
		log.Err(err, "When copying to a temporary file")
	}

	return tempDir, path, err
}
Esempio n. 29
0
// TODO set a defined max request size (currently set to 10MB in net/http/request.go)
func SaveFormFile(req *http.Request, resp http.ResponseWriter, path string) (*os.File, error) {
	// grab the file from the request
	f, h, err := req.FormFile("image")
	if err != nil {
		return nil, err
	}
	defer f.Close()

	// create the project path
	if err := os.MkdirAll(path, 0755); err != nil {
		return nil, err
	}

	// save the file
	t, err := os.OpenFile(filepath.Join(path, h.Filename), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return nil, err
	}
	defer t.Close()
	// copy the image to the file
	if _, err := io.Copy(t, f); err != nil {
		return nil, err
	}

	return t, nil
}
Esempio n. 30
0
func uploadHandler(w http.ResponseWriter, r *http.Request) {

	file, header, err := r.FormFile("file")

	if err != nil {
		fmt.Fprintln(w, err)
		return
	}
	defer file.Close()
	log.Println("Incoming: ", header.Filename)

	out, err := os.Create(path.Join("uploads", header.Filename))
	if err != nil {
		fmt.Fprintf(w, "Unable to create the file for writing. Check your write access privilege")
		return
	}

	defer out.Close()

	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Fprintln(w, err)
	}

	fmt.Fprintf(w, "File uploaded successfully: ")
	fmt.Fprintf(w, header.Filename)
	log.Println("Received: ", header.Filename)
}