从外部网址下载pdf文件 - Heroku,NodeJS,Angular 7



我正在尝试从外部源临时下载多个pdf文件到我的nodejs服务器(在Heroku中(,并将其上传到AWS S3 bucket。

我尝试了多种方法,所有这些方法在我的本地机器上都很好,但在Heroku Dyno NodeJS服务器上却不行。我甚至无法在Heroku中创建文件夹。我想是因为权限有限。

节点内

1( 使用var download=require('download-file'((目前在下面的代码中使用(

2( axios

3( res.download((

下载文件代码

const downloadFiles = async (unique_files) =>  {
for (let index = 0; index < unique_files.length; index++) {
let file_ext = unique_files[index].substr(unique_files[index].length - 4);
if(file_ext == ".pdf") {
await downloadzz(unique_files[index])
}
}
}
function downloadzz(link) {
download(link, function(err){ 
if (err) throw err
console.log("DOWNLOAD Complete");
});
}

上传文件代码

const uploadFiles = async (unique_files) =>  {
for (let index = 0; index < unique_files.length; index++) {
let file_ext = unique_files[index].substr(unique_files[index].length - 4);
if(file_ext == ".pdf") {
await uploadzz(unique_files[index])
}
}
}
function uploadzz(link) {
fs.readFile(require('path').resolve(__dirname+'/../external-pdfs/', link.slice(link.lastIndexOf('/') + 1)), function (err, data) {
params = {Bucket: pdfBucket, Key: link.slice(link.lastIndexOf('/') + 1), Body: data, ACL: "public-read" };
s3.putObject(params, function(err, data) {
if (err) {
console.log("Failed Upload", err);
} else {
console.log("Successfully uploaded data to bucket", data);
}
});
});
}

我没有收到任何错误,但在heroku服务器上似乎不存在名为外部pdfs的文件夹。

我对更好的解决方案持开放态度:例如,直接将文件从外部url上传到s3。。。如何从外部url读取文件并直接上传到AWS S3 bucket?

您可以使用axios。将responseType设置为stream,可以获取文件数据并将其作为正文传递。这里有一个从URL获取pdf并将其信息直接上传到S3的示例代码:

const AWS = require('aws-sdk');
const axios = require('axios');
AWS.config.loadFromPath('./config.json');
const s3 = new AWS.S3({apiVersion: '2006-03-01'});
const URL = "<YOUR_URL>";
const uploadPdfToS3 = async () => {
try{
const {data, headers} = await axios.get(URL, {responseType: 'stream'});
// Create params for putObject call
const objectParams = {
Bucket: "<YOUR_BUCKET>", 
Key: "<YOUR_KEY>", 
ContentLength: headers['content-length'],
Body: data
};
// Create object upload promise
await s3.putObject(objectParams).promise();
} catch(err){
console.log("ERROR --->" + err)
}
}

在Angular中,我们可以使用FileSaver库来保存库中的pdf文件。

找到下面的示例代码来执行此操作。在此处输入图像描述

最新更新