Bakr
Bakr

Reputation: 505

Download file from Express server

I tried to download file from my Express server. I'm sure the file is in a good location. It doesn't get errors, but the file is not downloaded anyway.

NodeJS:

const DOWNLOAD_FOLDER = 'downloads'
const IMAGES_FOLDER = 'images'

const express = require('express')
const fs = require('fs')


const app = express()
app.post('/', urlencodedParser, async (req, resp, next) => {    
  const filename = `test_file.zip`
  const downloadUrl = `./${DOWNLOAD_FOLDER}/${filename}.zip`
  
  if (fs.existsSync(downloadUrl)) {
    resp.download(`${__dirname}/${downloadUrl}`, (err) => {
      if (err) {
        console.log(err)
      } else {
        console.log('success')
      }
    })
  }
})


app.listen(5000).setTimeout(500000)
app.use(express.static(__dirname))

In the console, I see a console log("success"), but my browser doesn't download file.

React:

const submitHandler = async (e) => {
    e.preventDefault()
    setLoading(true)

    await fetch('http://localhost:5000/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 'url': data.url})
    })
    .then((data) => {
      console.log('data', data)
      setLoading(false)
      setData({ url: '' })
    })
    .catch(err => {
      throw new Error(err)
    })
  }

Upvotes: 1

Views: 182

Answers (1)

lotype
lotype

Reputation: 613

I think it is not necessary to make a fetch request. You might request only the URL by requesting the route with file name to be resolved via express. On client side you set the following:

window.location = `http://localhost:5000/${data.url}`

On the express side you change the method from post to get. You have to keep though the logic as to see the route and the file to be resolved dynamically.

Edit: Solution with fetch. It is also necessary to instruct the browser to download the file, e.g. by setting window.location

fetch(url).then(r => r.blob())
.then(img => {
  imgURL = URL.createObjectURL(img)
  window.location = imgURL;
})

Upvotes: 2

Related Questions