madmax80
madmax80

Reputation: 181

How do I download file from public folder in React using Express

I'm using Reactjs for client side and Express for server code.

I want to download a file located in the public/uploads folder called game.zip

This is my React component with download button.

import React, { Component, Fragment } from 'react';

class FileDownload extends Component {
    constructor(props) {
        super(props);
        this.state = {  }
    }
    render () {
        return ( 
            <Fragment>
                <div className="row">
                     <div className="container col-3">
                     <form method="GET" action="/download">
                        <input
                            type='submit'
                            value='Download'
                            className='btn btn-primary btn-block mt-4'
                        />
                        </form>

                    </div>
                </div>
                    
            </Fragment>
         );
    }
}
 
export default FileDownload;


This is my Express route inside server.js file.

app.get('/download', function(req, res){
    const file = `${__dirname}/client/public/uploads/game.zip`;
    res.download(file); // Set disposition and send it.
  });

This solution doesn't work, the express route isn't called.

Upvotes: 0

Views: 1768

Answers (1)

Lucas Said
Lucas Said

Reputation: 961

I think you don't need the form at all, try something like this instead:

<Fragment>
  <div className="row">
    <a 
      href="http://localhost:5000/download"
      target="_blank" 
      className="container col-3"
    >
      <button className='btn btn-primary btn-block mt-4'/>
    </a>
  </div>
</Fragment>

In the href attribute I assume you have your server listening on port 5000, you may change it to point to your server.

Also try the behavior without the target attribute, you might not need it

Upvotes: 2

Related Questions