[英]Upload HTML file to AWS S3 and then serving it instead of downloading
I am downloading a web page and then I am writing to a file named thisArticle.html
, using the below code. 我正在下载网页,然后使用以下代码写入名为thisArticle.html
的文件。
var file = fs.createWriteStream("thisArticle.html");
var request = http.get(req.body.url, response => response.pipe(file) );
After that I am trying to read file and uploading to S3, here is the code that I wrote: 之后,我尝试读取文件并上传到S3,这是我编写的代码:
fs.readFile('thisArticle.html', 'utf8', function(err, html){
if (err) {
console.log(err + "");
throw err;
}
var pathToSave = 'articles/ ' + req.body.title +'.html';
var s3bucket = new AWS.S3({ params: { Bucket: 'all-articles' } });
s3bucket.createBucket(function () {
var params = {
Key: pathToSave,
Body: html,
ACL: 'public-read'
};
s3bucket.upload(params, function (err, data) {
fs.unlink("thisArticle.html", function (err) {
console.error(err);
});
if (err) {
console.log('ERROR MSG: ', err);
res.status(500).send(err);
} else {
console.log(data.Location);
}
// ..., more code below
});
});
});
Now, I am facing two issues: 现在,我面临两个问题:
The file is uploading but with 0 bytes (empty) When I am trying to upload manually via S3 dashboard is uploaded successfully but when I tried to load the URL in the browser it downloads the HTML file instead of serving it. 该文件正在上载,但具有0字节(空),当我尝试通过S3仪表板手动上载时,成功上载,但是当我尝试在浏览器中加载URL时,它将下载HTML文件而不是将其提供。 Any guides if I am missing something? 如果我想念什么,有什么指导吗?
Set the ContentType to "text/html". 将ContentType设置为“ text / html”。
s3 = boto3.client("s3")
s3.put_object(
Bucket=s3_bucket,
Key=s3_key,
Body=html_string,
CacheControl="max-age=0,no-cache,no-store,must-revalidate",
ContentType="text/html",
ACL="public-read"
)
It looks like your upload function is deleting the file with fs.unlink
before it gets uploaded. 看来您的上传功能正在上传文件前先使用fs.unlink
删除该文件。 That's why its going up as 0 Bytes. 这就是为什么它上升为0字节的原因。
Also, to make the bucket serve the HTML, you need to turn on webserving as described in the AWS S3 Docs. 另外,要使存储桶为HTML提供服务,您需要按照AWS S3 Docs中的说明打开网络服务。 http://docs.aws.amazon.com/AmazonS3/latest/UG/ConfiguringBucketWebsite.html http://docs.aws.amazon.com/AmazonS3/latest/UG/ConfiguringBucketWebsite.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.