2.7 Handling Files with Gin
2.7.1 Static Files
In the Gin framework, you can use the built-in static file handling middleware to serve static files (e.g., images, CSS files, JS files, etc.). An example is shown below:
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
// Serve static files
r.Static("images", "./static/images/")
r.Run()
}
In the above code, the method <span>Static()</span> is used to provide static file services. The first parameter of the Static() method is the URL prefix for the static files, and the second parameter is the directory where the static files are located in the file system. Run the program and access the image by visiting the URL <span>http://127.0.0.1:8080/images/sample.png</span>.
2.7.2 Uploading Files
In the Gin framework, you can use the method <span>FormFile()</span> to handle file upload operations. The example code is as follows:
- HTML Example Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gin File Upload</title>
</head>
<body>
<p>File upload example:</p>
<br>
<form action="http://127.0.0.1:8080/upload_files" method="post" enctype="multipart/form-data" >
<input type="file" name="uploadFile" >
<button type="submit">Upload File</button>
</form>
</body>
</html>
- Backend Code:
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func uploadFiles(ctx *gin.Context) {
// Get the file to upload
f, err := ctx.FormFile("uploadFile")
if err != nil {
ctx.String(http.StatusBadRequest, "Failed to get file, error: %v", err)
return
}
// Specify the file save path
saveFilePath := fmt.Sprintf("./static/files/%s", f.Filename)
// Save the uploaded file
if err := ctx.SaveUploadedFile(f, saveFilePath); err != nil {
ctx.String(http.StatusInternalServerError, "Failed to save file, error: %v", err)
return
}
ctx.String(http.StatusOK, "File %v uploaded successfully", f.Filename)
}
func main() {
r := gin.Default()
// Handler function
r.POST("/upload_files", uploadFiles)
r.Run()
}
In the above code, a POST request route is defined for the URL (/upload_files) to handle file uploads. In the handler function, the <span>FormFile()</span> method is used to get the uploaded file, where the parameter <span>uploadFile</span> corresponds to the file field in the HTML form’s <span>name</span> attribute. After obtaining the file object, the <span>SaveUploadedFile()</span> method is used to save the uploaded file to the specified path. If the file is saved successfully, a 200 status code and a success message are returned; if saving fails, the corresponding error message is returned.
2.7.3 Downloading Files
In the Gin framework, you can respond to requests by sending files to the client. The example code is as follows:
package main
import (
"github.com/gin-gonic/gin"
)
func downloadFiles(ctx *gin.Context) {
// Get the actual path of the file
fp := "static/files/sample.zip"
// Send the file to the client
ctx.File(fp)
}
func main() {
r := gin.Default()
// Handler function
r.GET("/download_files", downloadFiles)
r.Run()
}
If you want to customize the filename when downloading the file, you can add the following code:
// If you want the downloaded file name to be different from the actual file name, you can add the following code
customeFilename := "ginDownloadFile.zip"
ctx.Header("Content-Disposition", "attachment;filename="+customeFilename)
If the file being downloaded is large, you need to send the file in streaming form to the client. The example code is as follows:
func downloadFilesStream(ctx *gin.Context) {
// Get the actual path of the file
fp := "static/files/sample.zip"
// Custom download file name
customeFilename := "ginDownloadFile.zip"
// Send the file to the client
ctx.FileAttachment(fp, customeFilename)
}
When using the
<span>FileAttachment()</span>method, the response header<span>Content-Disposition: attachment; filename="ginDownloadFile.zip"</span>is automatically set, and the file is sent to the client in streaming form, suitable for transferring larger files.