本文整理汇总了Golang中mime/multipart.File.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Close方法的具体用法?Golang File.Close怎么用?Golang File.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mime/multipart.File
的用法示例。
在下文中一共展示了File.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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)
}
示例2: 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
}
示例3: 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
}
示例4: 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
}
示例5: 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
}
示例6: 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)
}
示例7: 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)
}
示例8: 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
}
示例9: 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)
}
示例10: 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)
}
示例11: uploadPhoto
func uploadPhoto(m map[string]string, src multipart.File, hdr *multipart.FileHeader) map[string]string {
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(m, fName)
return m
}
示例12: uploadPhoto
func uploadPhoto(src multipart.File, hdr *multipart.FileHeader, c *http.Cookie) *http.Cookie {
defer src.Close()
fName := getSha(src) + filepath.Ext(hdr.Filename)
wd, _ := os.Getwd()
m := Model(c)
path := filepath.Join(wd, "assets", "imgs", m.Name, fName)
dst, _ := os.Create(path)
defer dst.Close()
src.Seek(0, 0)
io.Copy(dst, src)
return addPhoto("/imgs/"+m.Name+"/"+fName, c)
}
示例13: cropField
func cropField(field *gorm.Field, scope *gorm.Scope) (cropped bool) {
if field.Field.CanAddr() {
// TODO Handle scanner
if media, ok := field.Field.Addr().Interface().(Media); ok && !media.Cropped() {
option := parseTagOption(field.Tag.Get("media_library"))
if media.GetFileHeader() != nil || media.NeedCrop() {
var file multipart.File
var err error
if fileHeader := media.GetFileHeader(); fileHeader != nil {
file, err = media.GetFileHeader().Open()
} else {
file, err = media.Retrieve(media.URL("original"))
}
if err != nil {
scope.Err(err)
return false
}
media.Cropped(true)
if url := media.GetURL(option, scope, field, media); url == "" {
scope.Err(errors.New("invalid URL"))
} else {
result, _ := json.Marshal(map[string]string{"Url": url})
media.Scan(string(result))
}
if file != nil {
defer file.Close()
var handled = false
for _, handler := range mediaHandlers {
if handler.CouldHandle(media) {
file.Seek(0, 0)
if scope.Err(handler.Handle(media, file, option)) == nil {
handled = true
}
}
}
// Save File
if !handled {
scope.Err(media.Store(media.URL(), option, file))
}
}
return true
}
}
}
return false
}
示例14: SaveUploadedFile
func SaveUploadedFile(file multipart.File, fileName string) (string, error) {
tmpFile := "/tmp/" + fileName
f, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
log.Println("error uploading pic " + err.Error())
return "", err
}
_, err = io.Copy(f, file)
if err != nil {
log.Println("failed to copy file " + err.Error())
return "", err
}
file.Close()
f.Close()
return tmpFile, err
}
示例15: createFileInFS
func createFileInFS(file multipart.File, extension string) (string, error) {
defer file.Close()
newfilename := randomString()
imgfile, err := os.Create("tmp/" + newfilename + extension)
if err != nil {
return "", err
}
defer imgfile.Close()
_, err = io.Copy(imgfile, file)
if err != nil {
return "", err
}
return newfilename, nil
}