angularjs - 如何将文件转换为 .RAR 文件节点 js
问题描述
在我的项目中,我有一个项目表。每个项目都有一个下载 pdf 文件的栏目。现在我希望能够下载所有文件并创建一个 .rar 文件。有一个下载单个文件的代码:
路由.js
app.get('/api/download/archive/:filename', function(req,res){
res.download("public/uploads/"+req.params.filename, req.params.filename);
})
归档.js
$scope.downloadPdf = function(obj){
$http.get('api/download/archive/'+obj.Documentation)
.success(function(data){
window.open('api/download/archive/'+obj.Documentation)
});
}
解决方案
不幸的是,RAR 是一个闭源软件。因此,创建存档的唯一方法是安装名为的命令行实用程序rar
,然后rar a
在子进程中使用命令来压缩文件。
要rar
在 Mac 上安装,我必须运行brew install homebrew/cask/rar
. 您可以在此处找到其他平台的安装说明。
安装后可以child_process
这样使用:
const { exec } = require('child_process');
const { promisify } = require('util');
const fs = require('fs');
const path = require('path');
// Promisify `unlink` and `exec` functions as by default they accept callbacks
const unlinkAsync = promisify(fs.unlink);
const execAsync = promisify(exec);
(async () => {
// Generating a different name each time to avoid any possible collisions
const archiveFileName = `temp-archive-${(new Date()).getTime()}.rar`;
// The files that are going to be compressed.
const filePattern = `*.jpg`;
// Using a `rar` utility in a separate process
await execAsync(`rar a ${archiveFileName} ${filePattern}`);
// If no error thrown the archive has been created
console.log('Archive has been successfully created');
// Now we can allow downloading it
// Delete the archive when it's not needed anymore
// await unlinkAsync(path.join(__dirname, archiveFileName));
console.log('Deleted an archive');
})();
为了运行示例,请将一些.jpg
文件放入项目目录中。
PS:如果您选择不同的存档格式(例如 .zip),您将能够使用例如存档器之类的东西。这可能允许您创建一个 zip 流并将其通过管道直接响应。因此,您无需在磁盘上创建任何文件。但这是一个不同的问题。
推荐阅读
- python-3.x - 熊猫样式标签给出“ValueError:非唯一索引不支持样式”
- php - 如何将会话变量转换为 POST
- node.js - 即使 uid 不存在,Dgraph 查询也会返回数据
- slurm - SLURM:更改正在运行的阵列作业的最大同时运行任务数
- android - 房间 - 通过字符串查找对象的总和?
- java - 在java中使用鼠标在画布上绘制线条而不使用Swing
- javascript - 将 jQuery var 传递给进度条样式
- http - Arduino GET 方法链接
- python - 如何为 matplotlib 设置乳胶路径
- java - 使用 java 以编程方式在 keycloak 4.8.3 中创建用户