1. Uploading Files
1.beego website
View Upload Https://gowalker.org/github.com/astaxie/beego
2. Find the SaveToFile method
SaveToFile saves uploaded file to new path. It is only operates the first one of the Mutil-upload form file field.
Func (c *controller) SaveToFile (FromFile, tofile string) error {
File, _, Err: = C.ctx.request.formfile (fromfile) if err! = Nil { return err } defer file. Close () F, err: = OS. OpenFile (ToFile, OS. O_wronly|os. O_create|os. O_trunc, 0666) if err! = Nil { return err } defer f.close () io. Copy (f, file) return nil}
3. View the Beego document, and in the request parameters, upload the file
(1.) In form form, add the attribute enctype= "Multipart/form-data" to get the request parameter C.input (). Get ("id")
(2.) Beego provides two ways to handle file uploads:
GetFile (Key String) (multipart. File, *multipart. Fileheader, error)//This method is mainly used for the user to read the form of the file name The_file, and then return the corresponding information, the user according to these variables to handle file upload: Filtering, saving files, etc.
SaveToFile (FromFile, tofile String) error//This method is based on GetFile to implement the function of fast saving, FromFile is the name of the HTML form at the time of submission
(3.) Code example:
<form enctype= "Multipart/form-data" method= "POST" >
<input type= "File" name= "Uploadname"/>
<input type= "Submit" >
</form>
Func (c *formcontroller) Post () {
F, h, err: = C.getfile ("Uploadname")
If err! = Nil {
Log. Fatal ("GetFile err", err)
}
Defer F.close ()
C.savetofile ("Uploadname", "static/upload/" + h.filename)//save location in Static/upload, no folder to create first
}
(4.) File path name stitching
Path. Join ("path", fileName)//The function will use a different path delimiter depending on the operating system
(5.) Get the parameters from the URL
Requrl: = C.ctx.request.requesturi//For processing Chinese available URLs. Queryunescape (Requrl)
ID: = Strings. LastIndex (Requrl, "/")
Tid: = requrl[i+1:]
4. Using Golang native upload:
SaveToFile saves uploaded file to new path. It is only operates the first one of the Mutil-upload form file field.
Func (c *controller) SaveToFile (FromFile, tofile string) error {
File, _, Err: = C.ctx.request.formfile (fromfile) if err! = Nil { return err } defer file. Close () F, err: = OS. OpenFile (ToFile, OS. O_wronly|os. O_create|os. O_trunc, 0666) if err! = Nil { return err } defer f.close () io. Copy (f, file) return nil}