Preface
Today we will talk about how to use itGinImplement file upload.
GoStandard librarynet/httpVery comprehensive support has been provided for file uploads, andGinThe framework is further encapsulated on its basis, so it is usedGinWhen developing file upload function, it only takes a few simple lines of code to implement it.GinThe framework supports uploading of single files and multiple files simultaneously.
Use native net/http library to implement file upload
Let's first look at a simple example of implementing an HTTP server that provides file upload function
package main import ( "io" "io/ioutil" "log" "net/http" "/julienschmidt/httprouter" ) const ( MAX_UPLOAD_SIZE = 1024 * 1024 * 20 //Maximum upload size, 50MB) func main() { r := RegisterHandlers() (":8080", r) // Enable an http service} // Define the routefunc RegisterHandlers() * { router := () ("/upload", uploadHandler) return router } // File upload interfacefunc uploadHandler(w , r *, p ) { = (w, , MAX_UPLOAD_SIZE) if err := (MAX_UPLOAD_SIZE); err != nil { ("File is too big") return } file, headers, err := ("file") if err != nil { ("Error when try to get file: %v", err) return } //Get the uploaded file type if ("Content-Type") != "image/png" { ("Only upload png images") return } data, err := (file) if err != nil { ("Read file error: %v", err) return } fn := err = ("./video/"+fn, data, 0666) if err != nil { ("Write file error: %v", err) return } () (w, "Uploaded successfully") }
As mentioned above, we obtain the uploaded file object and file related information through functions. Then use the function to obtain the type of uploaded file to determine whether the type meets the requirements. Next, use the function to read the contents of the file and store it in the data variable. Then, by getting the file name of the uploaded file and using the function to write the file contents to the file under the specified path.
Use Gin to implement file upload
Single file upload
FormFile() gets the file
Single file uploadofFormFile()Method, the value of this method is the name of the file upload field in the POST request:
engine := () ("/upload", func(c *) { file, err := ("file") }) ()
SaveUploadedFile() to local
CallofSaveUploadedFile()Methods can save files to a directory:
dst := "./uploads/" + (file,"./uploadFile")
Set the buffer size
Go default file upload buffer is 32M. When a large number of files are uploaded, the server memory pressure will be very high, so it can be passedMaxMultipartMemoryProperties to set the buffer size:
//8M = 8 << 20
Limit file size
When uploading files, not limiting the file size can cause the service storage space to skyrocket, because there is a need to limit the uploaded file size:
fileMaxSize := 4 << 20 //4M if int() > fileMaxSize { (, "File size is not allowed to be smaller than 4M") return }
Limit file types
You can also restrict file types:
reader, err := () if err != nil { (err) return } b := make([]byte, 512) (b) contentType := (b) if contentType != "image/jpeg" && contentType != "image/png" { (, "File format error") return }
In the above code, we read the first 512 bytes of the file and call()This allows you to obtain the MIME value of the file.
Complete example
package main import ( "fmt" "log" "net/http" "/gin-gonic/gin" ) func main() { engine := () //8M = 8 << 20 ("/upload", func(c *) { file, err := ("file") if err != nil { (err) (, "File upload failed") return } fileMaxSize := 4 << 20 //4M if int() > fileMaxSize { (, "File size is not allowed to be 32KB") return } reader, err := () if err != nil { (err) return } b := make([]byte, 512) (b) contentType := (b) if contentType != "image/jpeg" && contentType != "image/png" { (, "File format error") return } dst := "./uploads/" + (file, dst) (, ("'%s' uploaded successfully!", )) }) () }
Test file upload
$ curl -F "file=@./" -X POST "http://localhost:8080/upload" '' Upload successfully!
Upload multiple files
MultipartForm() gets multiple files
If you want to upload multiple files, call them multiple timesofFormFile()The method is OK, but the better way is to use itofMultipartForm()method:
package main import ( "fmt" "log" "net/http" "/gin-gonic/gin" ) func main() { engine := () ("/uploadMul", func(c *) { form, err := () if err != nil { (err) (, "File upload failed") return } files := ["upload"] for _, file := range files { () } (, ("%d files uploaded!", len(files))) }) () }
Test file upload
After running the program, use the curl command to upload multiple files:
$ curl -F "upload=@./" -F "upload=@./" -X POST "http://localhost:8080/uploadMul 2 files uploaded
Summarize
GoStandard librarynet/httpVery complete support for file uploads can meet most of our needs.GinThe framework is encapsulated on its basis, making it more convenient and quick to use.
The above is the detailed content of the sample code that Golang uses Gin to implement file upload. For more information about Golang Gin file upload, please follow my other related articles!