将HTML文件上传到AWS S3,然后提供它而不是下载 [英] Upload HTML file to AWS S3 and then serving it instead of downloading

查看:493
本文介绍了将HTML文件上传到AWS S3,然后提供它而不是下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在下载网页,然后使用下面的代码写入名为 thisArticle.html 的文件.

I am downloading a web page and then I am writing to a file named thisArticle.html, using the below code.

var file = fs.createWriteStream("thisArticle.html"); 
var request = http.get(req.body.url, response => response.pipe(file) );

之后,我尝试读取文件并将其上传到S3,这是我编写的代码:

After that I am trying to read file and uploading to S3, here is the code that I wrote:

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:

文件正在上传,但有0个字节(空)当我尝试通过S3手动上传仪表板时,会成功上传,但是当我尝试在浏览器中加载URL时,它将下载HTML文件而不是将其提供.有什么指南可以帮助我吗?

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. Any guides if I am missing something?

推荐答案

将ContentType设置为"text/html".

Set the ContentType to "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"
    )

这篇关于将HTML文件上传到AWS S3,然后提供它而不是下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆