golang gin框架与前端交互如何返回文件给前端请写个示例
以下是一个简单的示例,演示如何使用Gin框架将文件返回给前端:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
// 定义路由,用于返回文件给前端
router.GET("/download", func(c *gin.Context) {
// 设置文件名和文件路径
filename := "example.txt"
filepath := "./example.txt"
// 打开文件
file, err := os.Open(filepath)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
defer file.Close()
// 设置响应头,告诉浏览器这是一个文件下载
c.Header("Content-Disposition", "attachment; filename="+filename)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Length", fmt.Sprint(fileInfo.Size()))
// 将文件内容写入响应
_, err = io.Copy(c.Writer, file)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
c.Status(http.StatusOK)
})
router.Run(":8080")
}
当用户访问 /download 路由时,服务器会读取指定文件的内容,并将其写入响应。浏览器会自动下载该文件,因为我们在响应头中设置了 Content-Disposition 为 attachment
原文地址: https://www.cveoy.top/t/topic/hafC 著作权归作者所有。请勿转载和采集!