node.js - 从 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)
})
}
解决方案
我认为没有必要发出 fetch 请求。您可以通过请求通过 express 解析文件名的路由来仅请求 URL。在客户端,您设置以下内容:
window.location = `http://localhost:5000/${data.url}`
在快递方面,您将方法从 更改post
为get
。您必须保持逻辑以查看要动态解析的路由和文件。
编辑:获取解决方案。还需要指示浏览器下载文件,例如通过设置window.location
fetch(url).then(r => r.blob())
.then(img => {
imgURL = URL.createObjectURL(img)
window.location = imgURL;
})
推荐阅读
- python - 如何在 Pandas 的 DataFrame 中处理时间?
- java - 如何在android xml中手动编写矢量可绘制pathData
- c# - C# "anyString".Contains('\0', StringComparison.InvariantCulture) 在 .NET5 中返回 true,但在旧版本中返回 false
- python - 我们可以使用 yaml BaseLoader 区分 yaml 文件中的字符串/int 值吗?
- regex - RegEx - 匹配最少两个单词
- java - 如何解决计算器应用程序上的 DecimalFormat 错误
- java - graphql-java 整数作为输入
- linux - 确定哪个主机(物理机)托管基于虚拟机(Vmware)的mac地址
- java - 任务':app:checkReleaseDuplicateClasses'的本机gradlew assembleRelease失败
- ios - Swift:使用 NSLock 或并发队列的安全线程