package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.POST("/upload", func(c *gin.Context) {
// 获取文件信息
file, header, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Bad request"})
return
}
defer file.Close()
// 创建保存路径
savePath := filepath.Join("./uploads", header.Filename)
out, err := os.Create(savePath)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
return
}
defer out.Close()
// 分块上传
buffer := make([]byte, 1024*1024) // 1MB 缓冲区
for {
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
return
}
if n == 0 {
break
}
_, err = out.Write(buffer[:n])
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
return
}
}
c.JSON(http.StatusOK, gin.H{"message": "File uploaded successfully"})
})
r.Run(":8080")
}
golang上传当处理大文件上传时,分块上传和流式上传
最新推荐文章于 2024-06-28 20:54:15 发布