【发布时间】:2022-10-13 19:13:28
【问题描述】:
我尝试允许用户上传文件并直接保存在 Google Cloud Storage 中。我使用 Node.js 作为服务器。
下面的代码有效,但是......
const uploadFile = async (req, res, next) => {
const file = bucket.file('sample/folder/file.txt');
// Create a pass through stream from a string
const passthroughStream = new stream.PassThrough();
passthroughStream.pipe(file.createWriteStream()).on('finish', () => {
// The file upload is complete
console.log('write-stream ended');
res.status(200).send({
succes: true
});
});
req.on('data', chunk => {
passthroughStream.write(chunk);
});
req.on('end', () => {
passthroughStream.end();
console.log('request ended');
});
};
我得到的是:
------WebKitFormBoundaryzsP9s0Bs6TksaKXo
Content-Disposition: form-data; name="teste.txt"; filename="teste.txt"
Content-Type: text/plain
... rest of the text file...
------WebKitFormBoundaryzsP9s0Bs6TksaKXo--
不确定是否重要,我创建了一个 8Mb 的 txt 文件以确保我会有更多的块。只有在结尾和开头我有这个txt。
我该如何摆脱它? 或者:如何以另一种方式做 id ?
【问题讨论】:
-
你检查过Signed URLs吗?您可以使用它们直接从客户端上传文件。
-
没有。我只知道使用签名网址下载。
-
它们也可以用来上传文件。您对后端进行 API 调用,这将生成一个签名 URL,然后客户端可以使用它将文件直接上传到 GCS。
-
可以作为一种解决方法,但我宁愿控制它。上传完成后我还需要在数据库中保存一些东西
-
您可以将 Cloud Storage Triggers 用于云函数,该函数将在文件上传后运行以运行某些逻辑。这样用户就不必等到图像上传到服务器然后再上传到 GCS。但也许你可以尝试将base64字符串传递给服务器,然后按照this answer上传到GCS>
标签: node.js google-cloud-platform google-cloud-storage