首页 > 解决方案 > 从 Express 服务器下载文件

问题描述

我试图从我的 Express 服务器下载文件。我确定该文件位于一个好的位置。它不会出错,但无论如何都不会下载文件。

节点JS:

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))

在控制台中,我看到一个控制台日志(“成功”),但我的浏览器没有下载文件。

反应:

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)
    })
  }

标签: node.jsexpress

解决方案


我认为没有必要发出 fetch 请求。您可以通过请求通过 express 解析文件名的路由来仅请求 URL。在客户端,您设置以下内容:

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

在快递方面,您将方法从 更改postget。您必须保持逻辑以查看要动态解析的路由和文件。

编辑:获取解决方案。还需要指示浏览器下载文件,例如通过设置window.location

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

推荐阅读