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


Golang multipart.File类代码示例

本文整理汇总了Golang中mime/multipart.File的典型用法代码示例。如果您正苦于以下问题:Golang File类的具体用法?Golang File怎么用?Golang File使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: uploadFile

func uploadFile(req *http.Request, mpf multipart.File, hdr *multipart.FileHeader) (string, error) {

	ext, err := fileFilter(req, hdr)
	if err != nil {
		return "", err
	}
	name := getSha(mpf) + `.` + ext

	rand.Seed(time.Now().Unix())
	x := rand.Intn(3)
	fmt.Println(x)

	var pfx string
	switch x {
	case 0:
		pfx = "bob/"
	case 1:
		pfx = "james/"
	case 2:
		pfx = "stacey/"
	}

	name = pfx + name

	mpf.Seek(0, 0)

	ctx := appengine.NewContext(req)
	return name, putFile(ctx, name, mpf)
}
开发者ID:mjrmyke,项目名称:GoLangCourse,代码行数:29,代码来源:file.go

示例2: ThumbnailMultipart

/**
takes a multipart file. Does not close it. creates a thumbnail and returns the file path
*/
func ThumbnailMultipart(file multipart.File, fileName string) (string, error) {
	var (
		err      error
		img      image.Image
		thumbImg *image.NRGBA
	)
	if _, err := file.Seek(0, 0); err != nil {
		log.Printf("failed to seek to beginning of img " + err.Error())
		return "", err
	}
	var thumbPath string = "/tmp/" + time.Now().String() + fileName
	img, _, err = image.Decode(file)
	if nil != err {
		log.Printf("failed to decode img " + err.Error())
		return "", err
	}

	thumbImg = imaging.Thumbnail(img, 300, 300, imaging.Lanczos)

	out, err := os.Create(thumbPath)

	if nil != err {
		log.Printf("failed to create thumb path " + err.Error())
		return "", err
	}

	defer out.Close()

	// write new image to file
	err = jpeg.Encode(out, thumbImg, nil)

	return thumbPath, err
}
开发者ID:maleck13,项目名称:locals-api,代码行数:36,代码来源:pics.go

示例3: generateThumbnails

func generateThumbnails(file multipart.File, userId, pathPrefix string, bucket *s3.Bucket) error {
	file.Seek(0, 0)

	img, _, err := image.Decode(file)
	if err != nil {
		log.Println("Error decoding image", err)
		return err
	}

	var buf bytes.Buffer
	for _, i := range THUMBNAIL_SIZES {
		resized := resize.Resize(uint(i), 0, img, resize.Lanczos3)
		err = jpeg.Encode(&buf, resized, nil)
		if err != nil {
			return err
		}
		path := fmt.Sprintf("%s/%d.jpg", pathPrefix, i)
		err = bucket.Put(path, buf.Bytes(), "image/jpeg", s3.PublicRead)
		if err != nil {
			return err
		}
		buf.Reset()
	}

	return err
}
开发者ID:AndrewJHart,项目名称:irlmoji,代码行数:26,代码来源:handlers_upload.go

示例4: StoreRelease

// StoreRelease saves what was uploaded. Buffered in case of large files.
func (r Release) StoreRelease(data multipart.File) {
	f, err := os.Create(r.ReleaseFilePath())
	if err != nil {
		log.Println("Can't open file: " + r.ReleaseFilePath())
		return
	}
	defer f.Close()

	buf := make([]byte, 1024)

	for {
		n, err := data.Read(buf)

		if err != nil && err != io.EOF {
			log.Println("Couldn't write file: " + r.ReleaseFilePath())
			break
		}

		if n == 0 {
			break
		}

		if _, err := f.Write(buf[:n]); err != nil {
			log.Println("Couldn't write file: " + r.ReleaseFilePath())
			break
		}
	}
}
开发者ID:geetarista,项目名称:fondu,代码行数:29,代码来源:release.go

示例5: Start

func (s ConsoleServer) Start() {
	// here is where I would specify the console interface if I actually planned on using the
	// from the command line.  For now it will just expect a command to look like `./calhoun
	// -ui=cli upload file=/path/to/file`
	url := s.Args[0]
	filepath := strings.SplitAfter(s.Args[1], "=")[1] // file=/path/to/file, so I need everything after the =

	var file multipart.File

	switch url {
	case "upload":
		file, err := os.Open(filepath)
		defer file.Close()

		if err != nil {
			log.Fatal("error reading photo upload: ", err)
		}
	default:
		log.Fatal("invalid command: `", url, "`")
	}

	route := s.routeWithPath(url)
	baseHandler := s.App.LookupHandler(route.Action)
	calhounHandler := route.ApplyMiddlewareToBase(baseHandler)
	request := CalhounRequest{UploadFile: &file}

	calhounHandler(os.Stdout, &request)
}
开发者ID:bentrevor,项目名称:calhoun,代码行数:28,代码来源:server.go

示例6: Exec

//Execute the file save process and return the result
func (f *filerSaver) Exec() (path string, status int, err error) {
	if _, err := os.Stat(f.path); err == nil {
		if err := os.MkdirAll(f.path, 0755); err == nil {
			var file multipart.File
			file, f.header, err = f.request.FormFile(f.key)
			if file != nil {
				defer file.Close()
			}
			if err == nil {
				fname := f.nameSetter(f.header.Filename)
				var fwriter *os.File
				path = filepath.Join(f.path, fname)
				fwriter, err = os.Create(path)
				if err == nil {
					defer fwriter.Close()
					_, err = io.Copy(fwriter, file)
				} else {
					status = SAVEFILE_COPY_ERROR
				}
			} else {
				status = SAVEFILE_FORMFILE_ERROR
			}
		} else {
			status = SAVEFILE_CREATE_DIR_ERROR
		}
	} else {
		status = SAVEFILE_STATE_DIR_ERROR
	}
	return
}
开发者ID:bjxujiang,项目名称:goblet,代码行数:31,代码来源:file_manager.go

示例7: Exec

//Execute the file save process and return the result
func (f *filerSaver) Exec() (path string, status int, err error) {
	// bug  if the path's stat is not ok, try make this dir.
	if _, err := os.Stat(f.path); err != nil {
		if err1 := os.MkdirAll(f.path, 0755); err1 != nil {
			//make dir fail,return status and err
			status = SAVEFILE_CREATE_DIR_ERROR
			return "", status, err1
		}
	}
	var file multipart.File
	file, f.header, err = f.request.FormFile(f.key)
	if file != nil {
		defer file.Close()
	}
	if err == nil {
		if fname, err := f.nameSetter(f.header.Filename); err == nil {
			var fwriter *os.File
			path = filepath.Join(f.path, fname)
			fwriter, err = os.Create(path)
			if err == nil {
				defer fwriter.Close()
				_, err = io.Copy(fwriter, file)
			} else {
				status = SAVEFILE_COPY_ERROR
			}
		} else {
			status = SAVEFILE_RENAME_ERROR_BY_USER
		}
	} else {
		status = SAVEFILE_FORMFILE_ERROR
	}
	return
}
开发者ID:extrame,项目名称:goblet,代码行数:34,代码来源:file_manager.go

示例8: Create

// Create takes the Profile Folder, a content-type (passed to S3), and the binary file
// data, and saves the file to S3, then saving the S3 information to the database.
// It returns the number of bytes sent to S3, for no particular reason, and any error.
func (p *Photo) Create(folder, ctype string, file multipart.File) (int64, error) {
	end, err := file.Seek(0, 2)
	if err != nil {
		return 0, err
	}
	_, err = file.Seek(0, 0)
	if err != nil {
		return 0, err
	}
	// ensure that folder actually exists in S3, here!
	b := s3Photos.Bucket(BaseBucket + "/" + folder)
	// ensure that folder exists... this doesn't error if it's already there
	err = b.PutBucket(s3.Private)
	if err != nil {
		return 0, err
	}
	err = b.PutReader(p.Href, file, end, ctype, s3.Private)
	if err != nil {
		return 0, err
	}

	err = dbmap.Insert(p)
	if err != nil {
		return 0, err
	}
	return end, nil
}
开发者ID:randallsquared,项目名称:gochute,代码行数:30,代码来源:profile.go

示例9: upload

func (s *Server) upload(wr http.ResponseWriter, r *http.Request) {
	var (
		vid    int64
		key    int64
		cookie int64
		size   int64
		err    error
		str    string
		v      *volume.Volume
		n      *needle.Needle
		file   multipart.File
		res    = map[string]interface{}{}
	)
	if r.Method != "POST" {
		http.Error(wr, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	defer HttpPostWriter(r, wr, time.Now(), &err, res)
	if err = checkContentLength(r, s.conf.NeedleMaxSize); err != nil {
		return
	}
	str = r.FormValue("vid")
	if vid, err = strconv.ParseInt(str, 10, 32); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", str, err)
		err = errors.ErrParam
		return
	}
	str = r.FormValue("key")
	if key, err = strconv.ParseInt(str, 10, 64); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", str, err)
		err = errors.ErrParam
		return
	}
	str = r.FormValue("cookie")
	if cookie, err = strconv.ParseInt(str, 10, 32); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", str, err)
		err = errors.ErrParam
		return
	}
	if file, _, err = r.FormFile("file"); err != nil {
		log.Errorf("r.FormFile() error(%v)", err)
		err = errors.ErrInternal
		return
	}
	if size, err = checkFileSize(file, s.conf.NeedleMaxSize); err == nil {
		n = s.store.Needle()
		if err = n.WriteFrom(key, int32(cookie), int32(size), file); err == nil {
			if v = s.store.Volumes[int32(vid)]; v != nil {
				err = v.Write(n)
			} else {
				err = errors.ErrVolumeNotExist
			}
		}
		s.store.FreeNeedle(n)
	}
	file.Close()
	return
}
开发者ID:yonglehou,项目名称:bfs,代码行数:58,代码来源:http_api.go

示例10: ServeHTTP

func (h httpUploadHandler) ServeHTTP(wr http.ResponseWriter, r *http.Request) {
	var (
		v                *Volume
		n                int
		vid, key, cookie int64
		err              error
		buf              []byte
		file             multipart.File
		res              = map[string]interface{}{"ret": RetOK}
	)
	if r.Method != "POST" {
		http.Error(wr, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	defer HttpPostWriter(r, wr, time.Now(), res)
	if err = r.ParseMultipartForm(NeedleMaxSize); err != nil {
		res["ret"] = RetInternalErr
		return
	}
	if vid, err = strconv.ParseInt(r.FormValue("vid"), 10, 32); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", r.FormValue("vid"),
			err)
		res["ret"] = RetParamErr
		return
	}
	if key, err = strconv.ParseInt(r.FormValue("key"), 10, 64); err != nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", r.FormValue("key"),
			err)
		res["ret"] = RetParamErr
		return
	}
	if cookie, err = strconv.ParseInt(r.FormValue("cookie"), 10, 64); err !=
		nil {
		log.Errorf("strconv.ParseInt(\"%s\") error(%v)", r.FormValue("cookie"),
			err)
		res["ret"] = RetParamErr
		return
	}
	if v = h.s.Volumes[int32(vid)]; v == nil {
		res["ret"] = RetNoVolume
		return
	}
	if file, _, err = r.FormFile("file"); err != nil {
		res["ret"] = RetInternalErr
		return
	}
	buf = v.Buffer()
	if n, err = file.Read(buf); err == nil {
		err = v.Add(key, cookie, buf[:n])
	}
	file.Close()
	v.FreeBuffer(buf)
	if err != nil {
		res["ret"] = RetUploadErr
	}
	return
}
开发者ID:qida,项目名称:bfs,代码行数:57,代码来源:http_api.go

示例11: UploadProfilePic

func UploadProfilePic(wr http.ResponseWriter, req *http.Request) {
	var (
		profileImgLoc string
		id            int64
		err           error
		p             *data.Profile
		file          multipart.File
		header        *multipart.FileHeader
		enc           *json.Encoder
	)

	enc = json.NewEncoder(wr)
	params := mux.Vars(req)
	id, err = strconv.ParseInt(params["id"], 10, 64)
	p, err = data.FindProfileById(id)
	req.ParseMultipartForm(10 << 20) //approx 10MB
	file, header, err = req.FormFile("file")

	handleUploadErr := func(err error, status int) {
		if nil != err {
			wr.WriteHeader(status)
			enc.Encode(NewErrorJSON(err.Error(), status))
		}
	}

	if err != nil {
		log.Println("error upload pic " + err.Error())
		handleUploadErr(err, http.StatusBadRequest)
		return
	}
	defer file.Close()
	uploadedFilePath, err := service.SaveUploadedFile(file, header.Filename)
	if err != nil {
		log.Println("failed to create thumbnail file  " + err.Error())
		handleUploadErr(err, http.StatusInternalServerError)
		return
	}

	uploadedFilePath, err = service.ThumbnailMultipart(file, header.Filename)
	if err != nil {
		log.Println("failed to create thumbnail file  " + err.Error())
		handleUploadErr(err, http.StatusInternalServerError)
		return
	}

	profileImgLoc, err = data.PutInBucket(uploadedFilePath, header.Filename)

	if err != nil {
		log.Println("failed up upload to s3 " + err.Error())
		handleUploadErr(err, http.StatusInternalServerError)
		return
	}

	p.UpdateProfilePic(profileImgLoc)
	enc.Encode(p)

}
开发者ID:maleck13,项目名称:locals-api,代码行数:57,代码来源:profile.go

示例12: saveUpload

func saveUpload(file multipart.File, handler *multipart.FileHeader) {
	defer file.Close()
	fmt.Printf("Uploaded file info: %#v", handler.Header)
	localFilename := fmt.Sprintf("./uploads/%v.%v", handler.Filename, submissions.NewToken())
	f, err := os.OpenFile(localFilename, os.O_WRONLY|os.O_CREATE, 0666)
	checkError(err)
	defer f.Close()
	_, err = io.Copy(f, file)
	checkError(err)
}
开发者ID:4honor,项目名称:build-web-application-with-golang,代码行数:10,代码来源:main.go

示例13: getMultipart

func getMultipart(r *knot.WebContext, fileName string) (server colonycore.ServerByType, payload colonycore.FileBrowserPayload, err error) {
	var tmp map[string]interface{}
	_, s, err := r.GetPayloadMultipart(&tmp)

	if err != nil {
		return
	}
	payload.ServerId = s["serverId"][0]
	payload.ServerType = s["serverType"][0]
	payload.Path = s["path"][0]

	err = r.Request.ParseMultipartForm(100000)
	if err != nil {
		return
	}

	m := r.Request.MultipartForm
	files := m.File[fileName]

	for key := range files {
		var file multipart.File
		file, err = files[key].Open()
		defer file.Close()
		if err != nil {
			return
		}

		payload.File = append(payload.File, file)
		payload.FileName = append(payload.FileName, s["filename"][key])

		tmpSize, _ := strconv.ParseInt(s["filesizes"][key], 10, 64)
		payload.FileSizes = append(payload.FileSizes, tmpSize)
	}

	query := dbox.Eq("_id", payload.ServerId)

	cursor, err := colonycore.Find(new(colonycore.Server), query)
	if err != nil {
		return
	}

	data := []colonycore.ServerByType{}
	err = cursor.Fetch(&data, 0, false)
	if err != nil {
		return
	}
	defer cursor.Close()

	if len(data) != 0 {
		server = data[0]
		server.ServerType = payload.ServerType
	}

	return
}
开发者ID:eaciit,项目名称:colony-manager,代码行数:55,代码来源:filebrowser.go

示例14: uploadPhoto

func uploadPhoto(src multipart.File, hdr *multipart.FileHeader, session *sessions.Session) {
	defer src.Close()
	fName := getSha(src) + ".jpg"
	wd, _ := os.Getwd()
	path := filepath.Join(wd, "assets", "imgs", fName)
	dst, _ := os.Create(path)
	defer dst.Close()
	src.Seek(0, 0)
	io.Copy(dst, src)
	addPhoto(fName, session)
}
开发者ID:RobertoSuarez,项目名称:GolangTraining,代码行数:11,代码来源:main.go

示例15: uploadPhoto

func uploadPhoto(src multipart.File, hdr *multipart.FileHeader, c *http.Cookie) *http.Cookie {
	defer src.Close()
	fName := getSha(src) + ".jpg"
	wd, _ := os.Getwd()
	path := filepath.Join(wd, "assets", "imgs", fName)
	dst, _ := os.Create(path)
	defer dst.Close()
	src.Seek(0, 0)
	io.Copy(dst, src)
	return addPhoto(fName, c)
}
开发者ID:GoesToEleven,项目名称:golang-web,代码行数:11,代码来源:photos.go


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