gpt4 book ai didi

javascript - 创建一个预签名的 url 并使用 Node js 将文件上传到谷歌云存储

转载 作者:搜寻专家 更新时间:2023-10-31 23:16:56 43 4
gpt4 key购买 nike

我需要使用签名 url 将文件上传到谷歌云存储。我需要通过不同的步骤上传。

  1. 使用 bucketName、服务 key 和所需的安全凭证创建一个 signedUrl。(使用任何 node.js 库)

  2. 使用 Postman 或 restClient 使用创建的签名 url 上传单个文件。

这是我创建用于上传的 signedUrl 的代码

var crypto = require("crypto");
var fs = require("fs");

var URL_VALID_DURATION = 1000 * 120;//for 120 seconds

var expiry = Math.floor(((new Date).getTime() + URL_VALID_DURATION) / 1000);

var key = 'filename';
var bucketName = 'bucketName';
var accessId = 'gserviceaccount.com';
var stringPolicy = "POST\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
var privateKey = fs.readFileSync("google-services-private-key.pem", "utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey, "base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key + "?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;

console.log(signedUrl);

但是我在使用 postman 或 rest client 时出错

<?xml version='1.0' encoding='UTF-8'?>
<Error>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message>
<StringToSign>PUT

multipart/form-data
1458024549
/bucketName/fileName</StringToSign>
</Error>

最佳答案

只是将 stringPolicy 方法更改为 PUT。并以二进制形式发送图像。

var crypto = require("crypto");
var fs = require("fs");

var URL_VALID_DURATION = 1000 * 120;//for 120 seconds

var expiry = Math.floor(((new Date).getTime() + URL_VALID_DURATION) / 1000);

var key = 'filename';
var bucketName = 'bucketName';
var accessId = 'gserviceaccount.com';
var stringPolicy = "PUT\n" + "\n" + "\n" + expiry + "\n" + '/' + bucketName + '/' + key;
var base64Policy = Buffer(stringPolicy, "utf-8").toString("base64");
var privateKey = fs.readFileSync("google-services-private-key.pem", "utf8");
var signature = encodeURIComponent(crypto.createSign('sha256').update(stringPolicy).sign(privateKey, "base64"));
var signedUrl = "https://" + bucketName + ".commondatastorage.googleapis.com/" + key + "?GoogleAccessId=" + accessId + "&Expires=" + expiry + "&Signature=" + signature;

console.log(signedUrl);

关于javascript - 创建一个预签名的 url 并使用 Node js 将文件上传到谷歌云存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36003782/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com