具有内容长度限制的签名URL

时间:2019-10-18 18:01:36

标签: node.js google-cloud-platform google-cloud-storage

我有以下代码为文件生成签名的上传网址:

const { Storage } = require('@google-cloud/storage');
const bucketName = 'foo-upload';
const storage = new Storage();
const uploadBucket = storage.bucket(bucketName);

exports.generateUploadLink = async (req, res) => {
  let contentId = req.query.contentId || req.body.contentId;

  let file = uploadBucket.file(`${contentId}.mp3`);

  try {
    let signedUrl = await file.getSignedUrl({
      action: 'write',
      expires: Date.now() + (30 * 1000),
      contentType: 'audio/mpeg'
    });
    res.status(200).json({meta: { status: 'OK'}, uploadUrl: signedUrl[0]});
  } catch(err) {
    console.log(`Error while getting signed url: ${err}`);
    res.status(500).json({meta: { status: 'FAIL', message: `Could not generate signed upload url for: ${contentId}`, error: err}});
  }
  return;
};

如何对已签名的网址强制执行内容长度限制,以使随后被PUT到某个特定字节数以上的网址的文件被拒绝?

1 个答案:

答案 0 :(得分:1)

您可以指定上传必须满足的政策文件。

Policy Document

设置content-length-range

一个示例,该示例将限制上传从0到1,000,000,000字节,并且仅针对内容类型image/jpeg

{
 "expiration": "2020-06-16T11:11:11Z",
 "conditions": [
  ["starts-with", "$key", "" ],
  {"acl": "bucket-owner-read" },
  {"bucket": "example-bucket"},
  {"success_action_redirect": "http://www.example.com/success_notification.html" },
  ["eq", "$Content-Type", "image/jpeg" ],
  ["content-length-range", 0, 1000000000]
  ]
}