0

I am generating files in my backend and keep them in memory.

I want to send the files with the ctx.Download method but it only accepts a String file path in disk.

How can I trigger a file download like Download method sending a []byte file in memory

  • Send appropriate Content-Disposition header. (And consider your need for fiber) – Volker Jul 05 '22 at 16:23
  • 1
    You could have your files stored in tmpfs (memory) and then serve them from there using string filename paths in Download method, just as you would for when the files are stored on disk. Obviously this is unix-specific approach. – jabbson Jul 05 '22 at 16:46

1 Answers1

0

I had a similar situation to what you describe, in that I wanted to download a file from an S3 bucket, but needed a file path for the Download() method. So, I wrote the contents of the file downloaded from the S3 bucket to a temporary file, then passed the temporary file's path to the Download() method.

Perhaps it's an approach that could work for you as well.

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)
Matthew Setter
  • 2,397
  • 1
  • 19
  • 18