问题描述
我正在使用 node 和 react 构建图像压缩器。服务器通过 res.download(filepath)
向客户端发送图像,但在客户端不会发生。 But I get the 200 OK response in the network and the image attachment。如何在客户端自动触发下载?
app.get('/download/:imageName',async (req,res)=>{
let imageName = req.params.imageName
let path = 'uploads/'+imageName;
//Image compression code
const compressedImage = await imagemin([path],{
destination: "output",plugins: [
imageminpngquant({
quality: [0.6,0.8]
}),imageminMozjpeg(),imagemingifsicle({lossy: 70}),imageminSvgo({
plugins: extendDefaultPlugins([
{name: 'removeViewBox',active: false}
])
})
]
});
// Here filepath = process.cwd()+"/"+compressedImage[0].destinationPath
res.download(process.cwd()+"/"+compressedImage[0].destinationPath)
})
function downloadAnImage(imageLink){
fetch("/download/"+imageLink)
}
顺便说一下,我没有在客户端处理响应,因为下载应该发生在 得到回应。
但是如果在浏览器中输入完整的图像 URL 路径,下载就会发生。然后我想我应该将完整的图像 URL 发送到客户端,但我找不到一个来获取我的服务器正在运行的主机 URL。我知道我的服务器正在运行的 URL,但是由于我要托管这个应用程序,手动将“localhost:3001”作为主机 url 是行不通的,对吗?
解决方法
我通过更改 downloadAnImage
函数解决了这个问题:
function downloadAnImage(imageLink){
let link=document.createElement('a');
link.href = process.env.REACT_APP_PROXY+"/download/"+imageLink
link.target = "_blank"
link.download = imageLink;
link.click();
}