如何使用Golang框架处理文件上传和下载?
时间:2024-07-02
浏览:496
作者:佚名
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《如何使用Golang框架处理文件上传和下载?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
Golang 文件上传和下载Golang 提供了处理文件上传和下载的强大机制:上传文件使用 r.ParseMultipartForm() 解析多部分表单数据从表单中获取文件生成唯一文件名并保存文件到磁盘下载文件从 URL 中提取文件路径打开文件并读取内容响应文件下载请求(例如使用 c.FileResponse())

在 Golang 中处理文件上传和下载
Golang 提供了强大的文件上传和下载机制,可以轻松集成到你的应用程序中。本文将介绍使用 Golang 处理文件上传和下载的最佳实践和实战案例。
文件上传
使用 FormFile 上传文件
import (
"encoding/json"
"io"
"net/http"
"github.com/google/uuid"
)
// handleFileUpload handles file upload requests
func handleFileUpload(w http.ResponseWriter, r *http.Request) {
// Parse multipart form
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, "Error parsing form", http.StatusBadRequest)
return
}
// Get file from form
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error getting file", http.StatusBadRequest)
return
}
// Generate a unique filename
filename := uuid.New().String() + "-" + header.Filename
// Save file to disk
destination, err := os.Create(filename)
if err != nil {
http.Error(w, "Error saving file", http.StatusInternalServerError)
return
}
defer destination.Close()
// Copy file data to disk
if _, err := io.Copy(destination, file); err != nil {
http.Error(w, "Error copying file data", http.StatusInternalServerError)
return
}
// Respond with success message
json.NewEncoder(w).Encode(map[string]string{"message": "File uploaded successfully"})
}文件下载
使用 FileResponse 下载文件
import (
"io"
"net/http"
"github.com/gin-gonic/gin"
)
// handleFileDownload handles file download requests
func handleFileDownload(c *gin.Context) {
// Get file path from context
filePath := c.Param("filepath")
// Open file for reading
file, err := os.Open(filePath)
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer file.Close()
// Create FileResponse
c.FileResponse(200, filePath, file)
}实战案例
Web 服务文件上传和下载演示
此案例展示了一个简单的 Web 服务,允许用户通过 REST API 上传和下载文件:
- 上传文件:发送一个 POST 请求到
/api/upload,带有文件字段。 - 下载文件:发送一个 GET 请求到
/api/download/{filePath},其中{filePath}是文件的路径。
可以通过克隆 GitHub 存储库查看完整代码:
git clone https://github.com/username/file-upload-download-service
本篇关于《如何使用Golang框架处理文件上传和下载?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
11.28
11.28
热门专题
