无法通过预签名URL访问Amazon S3存储桶中的PDF文件 [英] Unable to access PDF file in Amazon S3 bucket through presigned URL

查看:151
本文介绍了无法通过预签名URL访问Amazon S3存储桶中的PDF文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用React和Node从Amazon S3下载文件.我的想法是,当我单击客户端上的下载按钮时,文件下载应自动开始.到目前为止,我已经使用下面的代码设法从后端获取了预签名的URL.

I am learning to download files from Amazon S3 using React and Node. The idea is that when I click on a download button at the client-side, the file download should automatically start. Until now, I have managed to fetch the presigned URL from the backend using the code below.

index.js

const express = require("express");
const downloadRoutes = require("./routes/downloadRoutes");

const app = express();

app.use("/api/download", downloadRoutes);

app.listen(5000, () => {
  console.log("Server listening on port 5000");
});

routes/downloadRoutes.js

routes/downloadRoutes.js

const express = require("express");
const dotenv = require("dotenv");
const AWS = require("aws-sdk");

dotenv.config();

const router = express.Router();

const s3 = new AWS.S3({
  accessKeyID: process.env.AMAZON_ACESS_KEY_ID,
  secretAccessKey: process.env.AMAZON_SECRET_ACCESS_KEY,
});

router.get("/", (req, res) => {
  s3.getSignedUrl(
    "getObject",
    {
      Bucket: "download-hemanta-cv",
      ResponseContentType: "application/pdf",
      Key: "CV_Hemanta_Sundaray.pdf",
    },
    (err, url) => {
      console.log("Error", err, "url", url);
      if (err) {
        next(err);
      } else {
        res.send(url);
      }
    }
  );
});

module.exports = router;

我面临的问题是,当我将网址粘贴到chrome中时,我收到以下消息.

The problem I am facing is when I paste the URL in chrome I get the following message.

在浏览器中打开URL时如何查看PDF文件?

How can I see the PDF file when I open the URL in the browser?

推荐答案

对于发送到较新区域的请求,AWS S3需要签名V4.此处是文档的链接

AWS S3 needs signature V4 for requests sent to newer regions. Here is the link to documentation.

Amazon S3支持Signature Version 4(一种用于身份验证的协议)所有AWS区域中对AWS服务的入站API请求.在这到了2014年1月30日之前创建的AWS区域将继续支持以前的协议,签名版本2.任何新的区域2014年1月30日之后将仅支持Signature Version 4和因此,对这些区域的所有请求都必须带有签名版本4.

Amazon S3 supports Signature Version 4, a protocol for authenticating inbound API requests to AWS services, in all AWS regions. At this time, AWS Regions created before January 30, 2014 will continue to support the previous protocol, Signature Version 2. Any new Regions after January 30, 2014 will support only Signature Version 4 and therefore all requests to those Regions must be made with Signature Version 4.

要通过aws sdk发送已签名的请求,我们所需要做的只是在初始化对象时设置signatureVersion.

To send a signed request via aws sdk, all we need is to set the signatureVersion when initializing the object.

const s3 = new AWS.S3({
  region: 'ap-south-1',
  signatureVersion: "v4",
  accessKeyID: process.env.AMAZON_ACESS_KEY_ID,
  secretAccessKey: process.env.AMAZON_SECRET_ACCESS_KEY 
});

这篇关于无法通过预签名URL访问Amazon S3存储桶中的PDF文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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