当前位置: 首页>>代码示例>>Golang>>正文


Golang Request.FormFile方法代码示例

本文整理汇总了Golang中net/http.Request.FormFile方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.FormFile方法的具体用法?Golang Request.FormFile怎么用?Golang Request.FormFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.FormFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: BuildCreate

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)
}
开发者ID:gmelika,项目名称:rack,代码行数:60,代码来源:builds.go

示例2: handlePut

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
	}
}
开发者ID:kaveenherath,项目名称:SummerBootCamp,代码行数:27,代码来源:storage.go

示例3: uploadHandler

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
	}

}
开发者ID:pratikju,项目名称:go-chat,代码行数:30,代码来源:basic_handlers.go

示例4: uploadFileFromForm

// 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
}
开发者ID:jeffmendoza,项目名称:golang-samples,代码行数:35,代码来源:app.go

示例5: HelloServer

// 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)
}
开发者ID:leonardyp,项目名称:toolkits,代码行数:31,代码来源:http_multipart.go

示例6: uploadTextFile

// 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)

}
开发者ID:momazia,项目名称:GoTraining,代码行数:26,代码来源:main.go

示例7: ServeV1WriteNQuad

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
}
开发者ID:dennwc,项目名称:cayley,代码行数:34,代码来源:write.go

示例8: doConvert

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
}
开发者ID:ssor,项目名称:makeepub,代码行数:34,代码来源:server.go

示例9: GenPage

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"))
}
开发者ID:GavinMHaugen,项目名称:CSCI130,代码行数:30,代码来源:main.go

示例10: uploadHandler

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)
}
开发者ID:webvariants,项目名称:susi-gowebstack,代码行数:28,代码来源:susi-webstack.go

示例11: BindRequest

// 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
}
开发者ID:Xe,项目名称:go-swagger,代码行数:31,代码来源:upload_file_parameters.go

示例12: index

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)
}
开发者ID:mjrmyke,项目名称:GoLangCourse,代码行数:33,代码来源:main.go

示例13: uploads

////////////////////////////////
// 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)
	}
}
开发者ID:liamka,项目名称:Kayden-blog-engine,代码行数:36,代码来源:kayden.go

示例14: Paste

// 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)
}
开发者ID:lyuyun,项目名称:loggregator,代码行数:28,代码来源:pastehere.go

示例15: platformUpdate

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
}
开发者ID:zhenruyan,项目名称:tsuru,代码行数:33,代码来源:platform.go


注:本文中的net/http.Request.FormFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。