[英]Upload HTML file to AWS S3 and then serving it instead of downloading
我正在下載網頁,然后使用以下代碼寫入名為thisArticle.html
的文件。
var file = fs.createWriteStream("thisArticle.html");
var request = http.get(req.body.url, response => response.pipe(file) );
之后,我嘗試讀取文件並上傳到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
});
});
});
現在,我面臨兩個問題:
該文件正在上載,但具有0字節(空),當我嘗試通過S3儀表板手動上載時,成功上載,但是當我嘗試在瀏覽器中加載URL時,它將下載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"
)
看來您的上傳功能正在上傳文件前先使用fs.unlink
刪除該文件。 這就是為什么它上升為0字節的原因。
另外,要使存儲桶為HTML提供服務,您需要按照AWS S3 Docs中的說明打開網絡服務。 http://docs.aws.amazon.com/AmazonS3/latest/UG/ConfiguringBucketWebsite.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.