首页 > 解决方案 > 如何使用signedUrl将文件上传到谷歌云存储桶

问题描述

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

正如他们在上传文件的文档中提到的那样,我创建了一个生成签名 url 的函数,但是当我使用签名 url 发送文件时,浏览器中出现 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]
}

当我收到签名的 url 时,我将我的文件发送到其中,但它返回

No 'Access-Control-Allow-Origin' header is present on the requested resource.

标签: node.jsangulargoogle-cloud-platformcorsgoogle-cloud-storage

解决方案


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

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

您应该包含PUTmethod并放入*responseHeader因为Content-Type还不够


推荐阅读