我有一个基本的 Express 服务器和一个前端应用程序。当用户单击提交按钮时,我想向 Express 服务器发送请求,而 Express 服务器又应该为 Google Cloud Storage 存储桶生成签名 URL。从 Google Cloud Storage 成功获取签名 URL 后,它将被发送回前端,以便向包含所选输入视频文件的存储桶发出写入请求。 我看过很少有教程能够使用 AWS S3 存储桶来执行此操作,但我找不到使用 Google Storage Bucket 的教程。我尝试使用此代码:-
const storage = new Storage({
projectId: 'something',
keyFilename: 'test.json'
});
async function generateSignedUrl(bucketName, objectName) {
const expiration = new Date();
expiration.setMinutes(expiration.getMinutes() + 15);
const signedUrl = await storage.bucket(bucketName).file(objectName).getSignedUrl({
version: 'v4',
action: 'write',
expires: expiration,
});
return signedUrl;
}
// Your route to handle the request for a signed URL
app.get('/signed-url', async (req, res) => {
const bucketName = 'mycompanytestbucket';
const objectName = 'your-file-namethree.txt';
console.log('welcome')
const signedUrl = await generateSignedUrl(bucketName, objectName);
// Console log the signed URL
console.log(signedUrl);
// Send the signed URL back to the client
res.send(signedUrl);
});
在前端:-
const response = await fetch('http://localhost:8080/signed-url');
const signedUrl = await response.text();
const file = imageInput.files[0]
const xhr = new XMLHttpRequest();
xhr.open("PUT", signedUrl, true);
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
alert("File is uploaded");
} else {
alert("Something went wrong!");
}
};
xhr.onerror = () => {
alert("Something went wrong");
};
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
但是当我运行代码,选择一个文件,然后单击提交按钮时,我收到此错误:-
Failed to load resource: http://127.0.0.1:5500/frontend/[%22https://storage.googleapis.com/mycompanybucket/your-file-namethree.txt?X-G the server responded with a status of 405 (Method Not Allowed)
我还从google云存储桶权限中启用了allUsers权限,但仍然提示相同的错误。
任何有关实现这一目标的指南将不胜感激:)
在签名URL创建中添加方法
const signedUrl = await storage.bucket(bucketName).file(objectName).getSignedUrl({
version: 'v4',
method: 'PUT',
action: 'write',
expires: expiration,
});