【问题标题】:Upload HTML file to AWS S3 and then serving it instead of downloading将 HTML 文件上传到 AWS S3,然后提供它而不是下载
【发布时间】:2018-02-03 23:14:04
【问题描述】:

我正在下载一个网页,然后我正在使用以下代码写入一个名为 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 文件而不是提供它。 如果我遗漏了什么,有什么指南吗?

【问题讨论】:

    标签: javascript node.js amazon-web-services amazon-s3 server


    【解决方案1】:

    您的上传功能似乎在上传之前删除了带有fs.unlink 的文件。这就是它上升为 0 字节的原因。

    此外,要使存储桶为 HTML 提供服务,您需要按照 AWS S3 文档中的说明打开网络服务。 http://docs.aws.amazon.com/AmazonS3/latest/UG/ConfiguringBucketWebsite.html

    【讨论】:

    • 我评论说 fs.unlink 仍然上升为 0 字节。 @michael-j
    【解决方案2】:

    将 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"
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 2021-10-20
      • 2019-04-15
      • 1970-01-01
      • 2013-08-20
      • 2011-02-21
      相关资源
      最近更新 更多