node.js - 如何使用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.
解决方案
正如Brandon Yarbrough的回复中提到的,我必须在 Google Cloud 中配置 cors。我的配置中遗漏了一些东西
[
{
"origin": ["http://example.appspot.com"],
"responseHeader": ["*"],
"method": ["GET", "HEAD", "DELETE", "PUT"],
"maxAgeSeconds": 3600
}
]
您应该包含PUT
在method
并放入*
,responseHeader
因为Content-Type
还不够
推荐阅读
- python - Python将巨大的csv加载到postgresql
- python - Termux(Android 终端模拟器应用)上的 Python http.server 模块无法在本地网络 IP 地址上提供服务
- ubuntu - mkbundle f 中的网络标准问题。单声道6.6.0-ubuntu-18
- python-3.x - 向 pandas 数据框添加新列并插入与现有数据对应的数据
- javascript - 导入的 SVG 渲染为字符串
- reactjs - 尝试将 JSON 导入 React 组件时出错:“您可能需要适当的加载器”,但已安装正确的加载器
- c# - 在 ASP.NET MVC 中加密和解密密码
- firebase - Firebase 允许用户使用密钥进行访问
- git - 如何在 Flutter 中隐藏 API Keys 并且仍然能够让您的团队使用您的代码库?
- python - 有没有办法让python根据不断变化的日期变量来查找文件名?