Node.js如何压缩图像数组并强制浏览器下载
正如标题所说。我有一个可以从用户输入url收集所有图像url的应用程序。现在,我希望能够压缩它们,当用户按下下载按钮时,它将触发一个包含所有要下载的图像URL数组的请求,并让download.js处理下载 此外,我正在使用express.js和react;express.js正在使用端口5000 有人向我发送了一个工作示例代码: 但是,此代码将创建自己的端口3000 当express在端口5000上启动时,我希望能够在当前端口5000上处理下载 所以我修改了一些代码,但是,一旦我按下下载按钮,什么都没有发生(没有错误,也没有下载) 有人能告诉我怎么解决这个问题吗?谢谢 下载.jsNode.js如何压缩图像数组并强制浏览器下载,node.js,Node.js,正如标题所说。我有一个可以从用户输入url收集所有图像url的应用程序。现在,我希望能够压缩它们,当用户按下下载按钮时,它将触发一个包含所有要下载的图像URL数组的请求,并让download.js处理下载 此外,我正在使用express.js和react;express.js正在使用端口5000 有人向我发送了一个工作示例代码: 但是,此代码将创建自己的端口3000 当express在端口5000上启动时,我希望能够在当前端口5000上处理下载 所以我修改了一些代码,但是,一旦我按下下载按钮,什
const express = require('express');
let router = express.Router();
const fetch = require('node-fetch')
// to get the images const
JSZip = require('jszip')
// to zip them up
const micro = require('micro')
// to serve them
router.post('/download-pics', (req, res) => {
const files = [
{
url: "https://jeremyliberman.com/static/489f2e7cf7df14bc2c8ac2bc8c76aa59/cb864/avatar.png",
file: 'avatar.png'
},
{
url: "https://jeremyliberman.com/static/489f2e7cf7df14bc2c8ac2bc8c76aa59/cb864/avatar.png",
file: 'avatar1.png'
},
{
url: "https://jeremyliberman.com/static/489f2e7cf7df14bc2c8ac2bc8c76aa59/cb864/avatar.png",
file: 'avatar2.png' }
]
// Start a simple web service with one route
// Create an in-memory zip file
var zip = new JSZip();
// Fetch each image source
const request = async () => {
for (const { file, url } of files) {
const response = await fetch(url);
const buffer = await response.buffer();
zip.file(file, buffer);
}
}
request();
// Set the name of the zip file in the download
res.setHeader('Content-Disposition', 'attachment; filename="pictures.zip"')
// Send the zip file
zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true })
.pipe(res).on('finish', function() {
console.log("out.zip written.");
}) })
//export this router to use in our index.js module.exports = router;
函数
request
返回承诺。您需要在then(()=>{})中的request()
之后包装其余的代码
在调用zip.file()
之前,看起来您正在调用zip.generateNodeStream().pipe(res)
;ie:您正在生成一个没有内容的流。也许可以尝试等待请求()代码>?在何处添加等待请求()?为什么repl中的代码有效而我的代码无效?你解决了这个问题吗?我能够将数据返回到浏览器,但不知道如何将其作为zip加载
request()
.then(() => {
// Set the name of the zip file in the download
res.setHeader('Content-Disposition', 'attachment; filename="pictures.zip"')
// Send the zip file
zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true })
.pipe(res).on('finish', function() {
console.log("out.zip written.");
})
})