golang 文件上传和下载golang 提供了处理文件上传和下载的强大机制:上传文件使用 r.parsemultipartform() 解析多部分表单数据从表单中获取文件生成唯一文件名并保存文件到磁盘下载文件从 url 中提取文件路径打开文件并读取内容响应文件下载请求(例如使用 c.fileresponse())
在 Golang 中处理文件上传和下载
Golang 提供了强大的文件上传和下载机制,可以轻松集成到你的应用程序中。本文将介绍使用 Golang 处理文件上传和下载的最佳实践和实战案例。
文件上传
使用 FormFile 上传文件
import (
"encoding/json"
"io"
"net/http"
"<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15841.html" target="_blank">git</a>hub.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 存储库查看完整代码:
立即学习“go语言免费学习笔记(深入)”;
git clone https://github.com/username/file-upload-download-service