本文整理汇总了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)
}
示例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
}
}
示例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
}
}
示例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
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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"))
}
示例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)
}
示例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
}
示例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)
}
示例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)
}
}
示例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)
}
示例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
}