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


Golang Request.MultipartReader方法代码示例

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


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

示例1: POST

func (r *Resource) POST(c *ctx.Context, rw http.ResponseWriter, req *http.Request) error {
	reader, err := req.MultipartReader()
	if err != nil {
		return ctx.BadRequest(rw, c.T("media.uploadresource.could_not_upload_file"))
	}
	var tempFile *os.File
	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}

		tempFile, err = ioutil.TempFile(os.TempDir(), "spa")
		if err != nil {
			return ctx.InternalServerError(rw, c.T("media.uploadresource.could_not_create_temp_file"))
		}
		defer tempFile.Close()

		_, err = io.Copy(tempFile, part)
		if err != nil {
			break
		}
	}
	return ctx.Created(rw, tempFile.Name())
}
开发者ID:huuzkee-foundation,项目名称:gospa,代码行数:25,代码来源:resource.go

示例2: Upload

func Upload(res http.ResponseWriter, req *http.Request) {
	reader, err := req.MultipartReader()
	if err != nil {
		log.Fatal(err)
	}
	var processed []*rsp
	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		} else if err != nil {
			break
		}
		defer part.Close()
		if part.FileName() == "" {
			continue
		}
		key := strconv.FormatInt(time.Now().Unix(), 10)
		d, err := os.Create("tmp/" + key + "-" + part.FileName())
		if err != nil {
			log.Fatal(err)
		}
		defer d.Close()
		io.Copy(d, part)
		processed = append(processed, &rsp{part.FileName(), d.Name()})
	}
	response, err := json.Marshal(processed)
	if err != nil {
		log.Fatal(err)
	}
	res.Write(response)
}
开发者ID:Raggaer,项目名称:Upgoad,代码行数:32,代码来源:upload.go

示例3: UploadHandler

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	id := vars["id"]

	if _, exists := transfers[id]; exists {
		http.Error(w, "internal error", http.StatusBadRequest)
		return
	}

	mr, err := r.MultipartReader()
	if err != nil {
		http.Error(w, "internal error", http.StatusBadRequest)
		return
	}

	transfer := &Transfer{
		mr,
		WAIT,
	}
	transfers[id] = transfer

	timeout := time.After(time.Minute * time.Duration(conf.TimeoutMinutes))
	for transfer.Status == WAIT {
		select {
		case <-timeout:
			http.Error(w, "no receiver found", http.StatusBadRequest)
			transfer.Status = TIMEOUT
		}
	}
	w.Write([]byte("ok"))
}
开发者ID:henkman,项目名称:nethermes,代码行数:31,代码来源:main.go

示例4: NewNeedle

func NewNeedle(r *http.Request) (n *Needle, e error) {

	n = new(Needle)
	form, fe := r.MultipartReader()
	if fe != nil {
		log.Error("MultipartReader [ERROR] %s\n", fe)
		e = fe
		return
	}
	part, _ := form.NextPart()
	//log.Println("uploading file " + part.FileName())
	data, _ := ioutil.ReadAll(part)
	n.Data = data

	commaSep := strings.LastIndex(r.URL.Path, ",")
	dotSep := strings.LastIndex(r.URL.Path, ".")
	fid := r.URL.Path[commaSep+1:]
	if dotSep > 0 {
		fid = r.URL.Path[commaSep+1 : dotSep]
	}

	n.ParsePath(fid)

	return
}
开发者ID:xujianhai,项目名称:gopa,代码行数:25,代码来源:needle.go

示例5: handle

func handle(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		http.ServeFile(w, r, filepath.Join(static, "submit.html"))
		return
	}

	if r.Method == "POST" {
		files, err := r.MultipartReader()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		decks := make([]*Deck, 0)
		for {
			file, err := files.NextPart()
			if err == io.EOF {
				break
			}
			if file.FileName() == "" {
				continue
			}
			deck, err := NewDeck(file)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				fmt.Printf("Deck parse error: %s\n", err.Error())
				return
			}
			decks = append(decks, deck)
		}
		respond(w, decks)
	}
}
开发者ID:broady,项目名称:mtg-aggregatedeck,代码行数:32,代码来源:server.go

示例6: parseForm

func parseForm(w http.ResponseWriter, r *http.Request) *Upload {
	var upload Upload

	mp_rdr, err := r.MultipartReader()
	if err != nil {
		serverError(w, "error reading multipart: "+err.Error())
		return nil
	}

	for {
		part, err := mp_rdr.NextPart()

		if err == io.EOF {
			break
		}

		switch part.FormName() {
		case "file":
			upload.Data = readPart(part)
		case "filename":
			upload.Name = string(readPart(part))
		case "password":
			upload.Password = string(readPart(part))
		case "mode":
			upload.Mode = string(readPart(part))
		default:
			serverError(w, "invalid form part: "+part.FormName())
			return nil
		}
	}

	return &upload
}
开发者ID:johnzan,项目名称:talks,代码行数:33,代码来源:server.go

示例7: NewNeedle

func NewNeedle(r *http.Request) (n *Needle, fname string, e error) {

	n = new(Needle)
	form, fe := r.MultipartReader()
	if fe != nil {
		fmt.Println("MultipartReader [ERROR]", fe)
		e = fe
		return
	}
	part, _ := form.NextPart()
	fname = part.FileName()
	data, _ := ioutil.ReadAll(part)
	//log.Println("uploading file " + part.FileName())
	dotIndex := strings.LastIndex(fname, ".")
	if dotIndex > 0 {
		ext := fname[dotIndex:]
		mtype := mime.TypeByExtension(ext)
		if IsGzippable(ext, mtype) {
			data = GzipData(data)
		}
	}
	n.Data = data
	n.Checksum = NewCRC(data)

	commaSep := strings.LastIndex(r.URL.Path, ",")
	dotSep := strings.LastIndex(r.URL.Path, ".")
	fid := r.URL.Path[commaSep+1:]
	if dotSep > 0 {
		fid = r.URL.Path[commaSep+1 : dotSep]
	}

	n.ParsePath(fid)

	return
}
开发者ID:wangjinlei,项目名称:weedfs,代码行数:35,代码来源:needle.go

示例8: getUploadReader

func (i *webInterface) getUploadReader(r *http.Request) (io.ReadCloser, error) {

	mpr, err := r.MultipartReader()
	if err == http.ErrNotMultipart {
		// Not multipart, read raw body data
		return r.Body, nil
	}
	if err != nil {
		return nil, err
	}

	for {
		// Get next part of the upload
		part, err := mpr.NextPart()
		if err == io.EOF {
			return nil, errNoData
		}
		if err != nil {
			return nil, err
		}

		// Search for first file input
		fn := part.FileName()
		if fn != "" {
			return &partReader{
				p: part,
				b: r.Body,
			}, nil
		}
	}
}
开发者ID:cinode,项目名称:go,代码行数:31,代码来源:webinterface.go

示例9: getForm

// You should probably verify the content type is what you expect
// and at least basic validation of the file's contents. This,
// however, is the minimum required to upload a file to the server.
func getForm(w http.ResponseWriter, r *http.Request) {
	mp_rdr, err := r.MultipartReader()
	if err != nil {
		showPage(Page{false, nil}, w, r)
		return
	}
	var page Page
	var frm FormData
	for {
		part, err := mp_rdr.NextPart()
		if err == io.EOF {
			break
		}
		if part.FormName() == "caption" {
			br := new(bytes.Buffer)
			_, err := io.Copy(br, part)
			if err != nil {
				break
			}
			frm.Caption = string(br.Bytes())
		} else if part.FormName() == "image" {
			fileName := saveTempImage(part)
			if fileName == "" {
				break
			}
			frm.ImageFile = fileName
		}
	}
	if frm.ImageFile != "" && frm.Caption != "" {
		page.Processed = true
	}
	page.Image = &frm
	showPage(page, w, r)
}
开发者ID:gokyle,项目名称:webshell_tutorial,代码行数:37,代码来源:server.go

示例10: MultipartRequestReader

func MultipartRequestReader(r *http.Request) (io.Reader, string, error) {
	reader, err := r.MultipartReader()

	if err != nil {
		err = fmt.Errorf("MultipartRequestReader multipart reader error: %s", err)
		return nil, "", err
	}

	p, err := reader.NextPart()

	if err != nil {
		err = fmt.Errorf("MultipartRequestReader NextPart error: %s", err)
		return nil, "", err
	}

	name := p.FormName()

	if name == "" {
		return nil, "", fmt.Errorf("MultipartRequestReader missing field name")
	}

	filename := p.FileName()

	if filename == "" {
		return nil, "", fmt.Errorf("MultipartRequestReader part is not a file")
	}

	return p, filename, nil
}
开发者ID:koofr,项目名称:go-httputils,代码行数:29,代码来源:request_reader.go

示例11: HandleMultipleImagesUpload

// upload multiple images
func HandleMultipleImagesUpload(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	if req.ContentLength > helper.Config.MaxSize {
		http.Error(res, "file too large", http.StatusRequestEntityTooLarge)
		return
	}

	reader, err := req.MultipartReader()
	if err != nil {
		helper.WriteErrorResponse(res, err)
		return
	}
	var imgs []models.ImageInfo
	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}
		if part.FileName() == "" {
			continue
		}
		info, err := handleSaveSingleImage(part)
		imgs = append(imgs, info)
	}
	helper.WriteResponse(res, imgs)
}
开发者ID:yangsibai,项目名称:panda,代码行数:26,代码来源:image.go

示例12: upload

func upload(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		uploadTemplate.Execute(w, nil)
	} else {
		part_reader, err := r.MultipartReader()
		if err != nil {
			log.Println("get file:", err)
			w.WriteHeader(http.StatusInternalServerError)
		}
		log.Println("start copy")
		var file_part *multipart.Part
		for {
			if file_part, err = part_reader.NextPart(); err != nil {
				if err == io.EOF {
					err = nil
				}
				break
			}
			if file_part.FormName() == "file" {
				if err = write_file(file_part); err != nil {
					break
				}
			}
			file_part.Close()
		}
		if err != nil {
			log.Println("write file:", err)
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/upload", 302)
	}
}
开发者ID:datastream,项目名称:fileserver-pi,代码行数:33,代码来源:main.go

示例13: LoadTasksFromJson

func LoadTasksFromJson(r *http.Request, tasks *[]Task) (err error) {
	logger.Debug("LoadTasksFromJson(%v)", r.URL.Path)

	mpreader, err := r.MultipartReader()
	if err != nil {
		logger.Warn(err)
		return
	}

	frm, err := mpreader.ReadForm(10000)
	if err != nil {
		logger.Warn(err)
		return
	}

	jsonfile, err := frm.File["jsonfile"][0].Open()
	if err != nil {
		logger.Warn(err)
		return
	}
	defer jsonfile.Close()

	err = json.NewDecoder(jsonfile).Decode(&tasks)
	if err != nil {
		logger.Warn(err)
	}
	return
}
开发者ID:russ168,项目名称:golem,代码行数:28,代码来源:rest.go

示例14: MultipartReader

// MultipartReader returns a MIME multipart reader if this is a
// multipart/form-data POST request, else returns nil and an error.
// Use this function instead of ParseMultipartForm to
// process the request body as a stream.
func MultipartReader(r *http.Request) (*multipart.Reader, error) {
	_, err := r.MultipartReader()
	if err != nil {
		return nil, err
	}
	return multipartReader(r)
}
开发者ID:rfistman,项目名称:camlistore,代码行数:11,代码来源:multipart.go

示例15: uploadHandler

//This is where the action happens.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	//GET displays the upload form.
	case "GET":
		httplog.HttpLogln(r)
		display(w, "upload", nil)

	//POST takes the uploaded file(s) and saves it to disk.
	case "POST":
		//get the multipart reader for the request.
		httplog.HttpLogln(r)
		reader, err := r.MultipartReader()
		//		r.ParseMultipartForm(0)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		//copy each part to destination.
		for {
			part, err := reader.NextPart()
			if err == io.EOF {
				break
			}

			if part.FormName() == "path" {
				j, err := ioutil.ReadAll(part)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError) //do something
					return
				}
				log.Println(string(j))
				//log.Println(part)
			}

			//if part.FileName() is empty, skip this iteration.
			if part.FileName() == "" {
				continue
			}
			dst, err := os.Create("uploaded/" + part.FileName())
			defer dst.Close()

			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			if _, err := io.Copy(dst, part); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
		//display success message.
		display(w, "upload", "Upload successful.")
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}
开发者ID:neverlock,项目名称:upload,代码行数:60,代码来源:upload.go


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