我正在后端生成文件并将它们保存在内存中。
我想使用 ctx.Download 方法发送文件,但它只接受磁盘中的字符串文件路径。
如何触发文件下载,如 Download 方法在内存中发送 []byte 文件
我遇到了与您描述的情况类似的情况,因为我想从 S3 存储桶下载文件,但需要
Download()
方法的文件路径。因此,我将从 S3 存储桶下载的文件内容写入临时文件,然后将临时文件的路径传递给 Download()
方法。
也许这也是一种适合您的方法。
filename := "file1.txt"
file, err := os.CreateTemp("/tmp/", "temp-*.txt")
if err != nil {
return c.Status(fiber.StatusInternalServerError).
JSON(fiber.Map{
"error": true,
"msg": fmt.Sprintf("Couldn't create a temporary file to store the downloaded file. Reason: %v.\n", err),
})
}
defer os.Remove(file.Name())
body, err := io.ReadAll(result.Body)
if err != nil {
return c.Status(fiber.StatusInternalServerError).
JSON(fiber.Map{
"error": true,
"msg": fmt.Sprintf("Could not read contents of downloaded file. Reason: %v.\n", err),
})
}
_, err := file.Write(body)
if err != nil {
return c.Status(fiber.StatusInternalServerError).
JSON(fiber.Map{
"error": true,
"msg": fmt.Sprintf("Could not create temporary file with contents of downloaded file. Reason: %v.\n", err),
})
}
return c.Download(file.Name(), filename)
我能够像这样解决它:
var yourBytes []byte = ...
reader := bytes.NewReader(yourBytes)
c.Attachment("my-file-name.txt")
return c.SendStream(reader)
即使这不使用问题中要求的 ctx.Download() 方法,它仍然会触发浏览器中该文件的“下载”,这可能就是想要的。