如何使用签名的URL将文件上传到Google云端桶

问题描述 投票:0回答:2

我正在开发一个Angular App,用于显示谷歌云存储桶的内容。对于后面,我在nodeJS中使用谷歌云功能

正如他们在文档中提到的上传文件一样,我创建了一个生成签名网址的函数,但是当我使用签名网址发送我的文件时,我在浏览器中遇到了一个cors错误

我用邮递员测试过,它上传了一个空文件

这是我的lambda函数:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

exports.generateSignedUrl = (req, res) => {
// generate signed url to use for file upload

const filename = req.query.fileName;
console.log('filename ', filename);

const filetype = req.query.fileType;
console.log('filetype ', filetype);

const bucketName = 'nx-terega-omega';

res.set('Access-Control-Allow-Origin', "*");
res.set('Access-Control-Allow-Headers', "Origin, X-Requested-With, 
Content-Type, Accept, Authorization");

if (req.query.fileName !== null && req.query.fileName !== undefined
  && req.query.fileType !== null && req.query.fileType !== undefined) 
{
generateV4UploadSignedUrl(bucketName, filename).then(function (value) 
{
  console.log('File Url response ', value);
  res.status(200).send(JSON.stringify({'url': value}));
}).catch(error => {
  res.status(404).send('Error while generating signed url');
});
} else {
res.status(500).send('Filename not found');
}
};

async function generateV4UploadSignedUrl(bucketName, filename, filetype) {
// [START storage_generate_upload_signed_url_v4]

// These options will allow temporary uploading of the file with outgoing
// Content-Type: application/octet-stream header.
const options = {
version: 'v4',
action: 'write',
expires: Date.now() + 15 * 60 * 1000, // 15 minutes
contentType: filetype,
};

// Get a v4 signed URL for uploading file
const [url] = await storage
.bucket(bucketName)
.file(filename)
.getSignedUrl(options);

console.log('Generated PUT signed URL:');
console.log(url);
console.log('You can use this URL with any user agent, for example:');
console.log("curl -X PUT -H 'Content-Type: application/octet-stream' " +`--upload-file my-file '${url}'`);

return url;
// [END storage_generate_upload_signed_url_v4]
}

当我收到签名的网址时,我将其文件发送给我,但它会返回

No 'Access-Control-Allow-Origin' header is present on the requested resource.
node.js angular google-cloud-platform cors google-cloud-storage
2个回答
1
投票

签名URL使用GCS的XML API。该API允许跨源请求,但默认情况下不启用它。您需要为存储桶指定CORS策略。

例如,您可以创建如下的CORS策略(假设这是一个名为policy.json的文件):

[
    {
      "origin": ["http://example.appspot.com"],
      "responseHeader": ["Content-Type"],
      "method": ["GET", "HEAD", "DELETE"],
      "maxAgeSeconds": 3600
    }
]

CORS政策文件的完整描述如下:https://cloud.google.com/storage/docs/xml-api/put-bucket-cors#request_body_elements

现在让我们将该策略应用于存储桶:

gsutil cors set policy.json gs://my-bucket-name

该文档有更多关于在存储桶上启用CORS的说明:https://cloud.google.com/storage/docs/configuring-cors


1
投票

正如Brandon Yarbrough的回应中提到的,我不得不在Google Cloud中配置cors。我在配置中遗漏了一些东西

[
 {
  "origin": ["http://example.appspot.com"],
  "responseHeader": ["*"],
  "method": ["GET", "HEAD", "DELETE", "PUT"],
  "maxAgeSeconds": 3600
 }
]

你应该在PUT中包括method并将*放在responseHeader中,因为Content-Type不够

© www.soinside.com 2019 - 2024. All rights reserved.