Go语言使用Gin框架实现文件流下载
Go语言使用Gin框架实现文件流下载
本文将介绍如何使用Go语言的Gin框架,将后端数据,例如 newInspect 对象,转换为JSON格式,并以文件流的方式下载到前端。
以下代码片段展示了如何实现该功能:
func (srv *ContainerService) ExportContainer(c *gin.Context, user string) {
result, _, err := srv.cli.ContainerInspectWithRaw(context.Background(), req.Id, false)
if err != nil {
logger.Error(err.Error())
}
marshal, err := json.Marshal(result)
if err != nil {
logger.Error(err.Error())
}
var newInspect dto.ExportResp
err = json.Unmarshal(marshal, &newInspect)
if err != nil {
logger.Error(err.Error())
}
raw, _, err := srv.cli.ImageInspectWithRaw(context.Background(), inspect.Image)
if err != nil {
logger.Error(err.Error())
}
split := strings.Split(raw.RepoTags[0], ':')
newInspect.ImageName = split[0]
newInspect.ImageVersion = split[1]
i, err := json.Marshal(newInspect)
if err != nil {
logger.Error(err.Error())
}
reader := bytes.NewReader(i)
c.Header('Content-Disposition', 'attachment; filename='+req.Name)
c.Header('Content-Type', 'application/octet-stream')
_, err = io.Copy(c.Writer, reader)
if err != nil {
c.String(http.StatusInternalServerError, 'Failed to write response stream')
return
}
c.Status(http.StatusOK)
}
代码解释:
- 首先,代码获取需要传递给前端的数据,例如
result对象,并将其转换为 JSON 字符串。 - 然后,将 JSON 字符串解析为
newInspect对象,并使用该对象的信息获取相关的镜像信息。 - 将最终需要传递给前端的数据,例如
newInspect对象,转换为 JSON 字符串,并使用bytes.NewReader将其转换为字节流reader。 - 设置响应头,包括
Content-Disposition和Content-Type,告知浏览器将响应内容作为附件下载,并指定文件类型为application/octet-stream。 - 使用
io.Copy将字节流reader写入到gin.Context的Writer中,实现文件流下载。 - 最后,设置响应状态码为
http.StatusOK,表示下载成功。
通过以上步骤,就可以使用 Gin 框架将后端数据以文件流的方式下载到前端,方便用户保存和使用数据。
原文地址: https://www.cveoy.top/t/topic/fU4m 著作权归作者所有。请勿转载和采集!