DEV Community

Cover image for How to use res.download() to download images
Christopher Howard
Christopher Howard

Posted on

How to use res.download() to download images

What does res.download() do?

An express.js method that downloads the file at the path specified as an attachment. It takes these arguments.

Path — string, the path to the file you want to download.

Filename — string, the file name you want to call the file, if absent will use the filename in the path.

Options — object, an object used to specify options.

Callback — function, a function to do when it completes successfully or throws an error.

Using res.download() normally

Here I'm going to make a html document with 2 buttons in it.

The html for the article res.download().
When I click the first button I'll reroute the browser with window.location.href to the "/download" route on the express server.

The javascript for res.download()
On the server, I'll make a get request to the "/download" route. In the response, I'll use the res.download() method with the path, filename & callback functions specified. When it comes back successful, I'll console.log() a message. The file will be downloaded when I hit this route. Also, the browser will remain on the same view or page even since res.end() was called instead of res.render() or res.redirect.

The res.download() method on the server

Res.download() automatically calls res.end()

When res.download() completes successfully it automatically calls res.end() after the callback function. That means you don't need to call res.end(), res.json() or any other method that ends the response. Doing so will throw an error.

Res.download() errors

When calling a method that ends res.download(), you will receive a headers already sent error. This means that res.end() was called twice. To check for this, you could see if res.headersSent property is true. This property checks to see if a response was already sent.

Checking the error on res.download() method
The other error that will be thrown is if the path to file is wrong or the file being downloaded does not exist. If this happens you'll want to send a response status saying the file is not found.

The file not found error on res.download()

Using res.download() with fetch request

If you need to use fetch to send some form info or do something else, you will have to make a middleman route an order to use res.download(). Res.download() will fire, but it will not download the file. I made a call to "/downloadImage" route, then returned a message. When the fetch request completes, I then reroute the browser to the "/download" route to get the file.

The fetch to download an image.

Extras

The express docs for res.download() says that browsers will prompt the user for download. I have not run into this myself. Here is code putting res.download() into action.
To find more articles from me visit webplayground.

Top comments (0)