Home > Article > Backend Development > How to implement asynchronous file upload using Golang?
How to implement asynchronous file upload using Go? Use http.MultipartFile to handle file uploads, which supports concurrent uploads. Create a goroutine to upload files asynchronously without blocking the main thread. Use io.Copy to write the file contents to a new file. Print a log message after successful upload.
How to use Golang to implement asynchronous file upload
Asynchronous file upload is a technology that allows you to upload files without blocking the main thread. In this case, upload the file to the server. This is useful for large file uploads or applications that need to continue performing tasks during the upload. The Go language provides a built-in http.MultipartFile
type to handle file uploads, which supports concurrent uploads.
Code example
The following is an example of using Go language to implement asynchronous file upload:
package main import ( "context" "fmt" "io" "log" "net/http" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() // 文件上传处理程序 router.POST("/upload", func(c *gin.Context) { // 获取 multipart 文件 file, header, err := c.Request.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": fmt.Sprintf("获取文件失败: %s", err.Error()), }) return } // 创建一个 goroutine 来异步上传文件 go func() { ctx := context.Background() // 创建一个新文件并在其中写入 dst, err := os.Create(fmt.Sprintf("uploads/%s", header.Filename)) if err != nil { log.Printf("创建文件失败: %s", err.Error()) return } defer dst.Close() if _, err := io.Copy(dst, file); err != nil { log.Printf("写入文件失败: %s", err.Error()) return } log.Printf("文件 %s 已成功上传", header.Filename) }() c.JSON(http.StatusOK, gin.H{ "status": "success", }) }) router.Run(":8080") }
Practical case
This example is a simple file upload service that can upload files to the server through POST
requests. The file is asynchronously uploaded to the uploads
directory, and a log message is printed when the upload is successful.
Run the example
go run main.go
. POST
request to http://localhost:8080/upload
, which contains a file named file
file fields. If the file uploaded successfully, you should see a log message similar to The file example.txt was successfully uploaded
.
The above is the detailed content of How to implement asynchronous file upload using Golang?. For more information, please follow other related articles on the PHP Chinese website!