Implementing file upload and download
Gin is a Web development framework developed using Go language. It has the characteristics of high efficiency, ease of use and flexibility. For file uploading and downloading, these functions can be easily implemented using the Gin framework. This article will introduce how to use the Gin framework to upload and download files.
1. File upload
In the Gin framework, file upload requires the use of the MultipartForm form. First, you need to define routing and processing functions:
router.POST("/upload", uploadHandler)
func uploadHandler(c *gin.Context) {
file, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } filename := filepath.Base(file.Filename) if err := c.SaveUploadedFile(file, filename); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } c.JSON(http.StatusOK, gin.H{ "message": fmt.Sprintf("'%s' uploaded!", filename), })
}
In the processing function for uploading files, first obtain the uploaded file through the c.FormFile() function and perform error handling. Then get the file name and use the c.SaveUploadedFile() function to save the file to the specified directory. Finally, the upload results are returned via JSON.
Start the Gin service and visit http://localhost:8080/upload. You will see the following interface:
https://user-images.githubusercontent.com/36320997/129822689- f45e849c-7cae-4ad9-9107-aae98f76d34c.png
After the file is uploaded successfully, you will see the following JSON return result:
{
"message": "'test.txt' uploaded!"
}
2. File download
File downloading requires the static file service of the Gin framework. This can be achieved through the following operations:
1. Create any directory in the application to save downloaded files.
2. In Gin routing, define access to files in this directory, as follows:
router.StaticFS("/download", http.Dir("tmp"))
3. In the routing processing function, define the download interface based on the file name, as follows:
router.GET("/download/:filename", downloadHandler)
func downloadHandler(c *gin.Context) {
filename := c.Param("filename") file := "./tmp/" + filename // 通过配置文件获取下载目录地址,如: "./tmp/" + filename fi, err := os.Stat(file) if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) return } c.Writer.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fi.Name())) c.Writer.Header().Set("Content-Type", "application/octet-stream") c.File(file)
}
In the file download processing function, you need to obtain the file name through c.Param(), determine whether the file exists, and set the download HTTP response header. Finally, the file is written into the response to implement the file download function.
Start the Gin service and visit the following link http://localhost:8080/download/test.txt to download the test.txt file.
3. Summary
The file upload and download functions are implemented through the Gin framework, which is elegant and concise. The above code is only the basic implementation. In actual use, you also need to consider the location and method of file storage, as well as subsequent file operations, etc. Readers can improve it based on their own actual conditions.
The above is the detailed content of How to golang gin. For more information, please follow other related articles on the PHP Chinese website!

This article explains Go's package import mechanisms: named imports (e.g., import "fmt") and blank imports (e.g., import _ "fmt"). Named imports make package contents accessible, while blank imports only execute t

This article explains Beego's NewFlash() function for inter-page data transfer in web applications. It focuses on using NewFlash() to display temporary messages (success, error, warning) between controllers, leveraging the session mechanism. Limita

This article details efficient conversion of MySQL query results into Go struct slices. It emphasizes using database/sql's Scan method for optimal performance, avoiding manual parsing. Best practices for struct field mapping using db tags and robus

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article details efficient file writing in Go, comparing os.WriteFile (suitable for small files) with os.OpenFile and buffered writes (optimal for large files). It emphasizes robust error handling, using defer, and checking for specific errors.

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
