S3 预签名 URL 多内容配置标头

abd*_*wer 10 amazon-s3 content-disposition amazon-web-services node.js pre-signed-url

我有一个 S3 存储桶,其中包含 PDF 文件作为对象,并且所有文件都是私有的。我以编程方式创建一个 S3 预签名 URL 来获取该对象。效果很好。现在,我希望它可以以 PDF 形式预览。每个对象都已经有一个Content-Type设置为 的标头application/pdf。现在,如果我将response-content-disposition标头设置为查询参数,它会被设置但不会覆盖已经存在的Content-disposition标头,而是创建一个新标头。如果我Content-Disposition在 S3 对象的元数据中设置标头,而不是将其作为查询参数添加到 S3 预签名 URL 中,它仍然显示 2 个标头。这是 AWS S3 端的某种错误吗?

以下是响应标头的屏幕截图以供参考。

骗局

任何帮助都感激不尽。谢谢。

abd*_*wer 15

我使用以下代码使用 AWS SDK for NodeJS 提供的最新 API 解决了这个问题:

const aws = require('aws-sdk');

const AWS_SIGNATURE_VERSION = 'v4';

const s3 = new aws.S3({
  accessKeyId: <aws-access-key>,
  secretAccessKey: <aws-secret-access-key>,
  region: <aws-region>,
  signatureVersion: AWS_SIGNATURE_VERSION
});

/**
 * Return a signed document URL given a Document instance
 * @param  {object} document Document
 * @return {string}          Pre-signed URL to document in S3 bucket
 */
const getS3SignedDocumentURL = (docName) => {
  const url = s3.getSignedUrl('getObject', {
    Bucket: <aws-s3-bucket-name>,
    Key: <aws-s3-object-key>,
    Expires: <url-expiry-time>,
    ResponseContentDisposition: `attachment; filename="${docName}"`
  });

  return url;
};

/**
 * Return a signed document URL previewable given a Document instance
 * @param  {object} document Document
 * @return {string}          Pre-signed URL to previewable document in S3 bucket
 */
const getS3SignedDocumentURLPreviewable = (docName) => {
  const url = s3.getSignedUrl('getObject', {
    Bucket: <aws-s3-bucket-name>,
    Key: <aws-s3-object-key>,
    Expires: <url-expiry-time>,
    ResponseContentDisposition: `inline; filename="${docName}"`
  });

  return url;
};

module.exports = {
  getS3SignedDocumentURL,
  getS3SignedDocumentURLPreviewable
};

Run Code Online (Sandbox Code Playgroud)

注意:不要忘记用实际值替换占位符 (<...>) 以使其工作。