目前,我正在使用@google-cloud/storageNPM软件包将文件直接上传到谷歌云存储桶.这需要一些技巧,因为我只有图像的base64编码字符串.我必须:

  • 解码字符串
  • 将其另存为文件
  • 将文件路径发送到下面的脚本,以上传到谷歌云存储
  • 删除本地文件

我希望避免将文件完全存储在文件系统中,因为我使用的是Google App Engine,如果删除操作因任何原因无法工作,我不想使文件系统过载/将垃圾文件留在文件系统中.这就是我的上传脚本现在的样子:

// Convert the base64 string back to an image to upload into the Google Cloud Storage bucket
var base64Img = require('base64-img');
var filePath = base64Img.imgSync(req.body.base64Image, 'user-uploads', 'image-name');

// Instantiate the GCP Storage instance
var gcs = require('@google-cloud/storage')(),
    bucket = gcs.bucket('google-cloud-storage-bucket-name');

// Upload the image to the bucket
bucket.upload(__dirname.slice(0, -15) + filePath, {
    destination: 'profile-images/576dba00c1346abe12fb502a-original.jpg',
    public: true,
    validation: 'md5'
}, function(error, file) {

    if (error) {
        sails.log.error(error);
    }

    return res.ok('Image uploaded');
});

是否可以直接上传图像的base64编码字符串,而不必将其转换为文件,然后使用路径上传?

推荐答案

我认为,解决方案是使用Google Cloud Node SDK中bucket.upload函数包装的file.createWriteStream个功能.

我对streams几乎没有什么经验,所以如果这不起作用,请尽量容忍我.

首先,我们需要获取base64数据并将其放入流中.为此,我们将包括stream库,从base64数据创建一个缓冲区,并将该缓冲区添加到流的末尾.

var stream = require('stream');
var bufferStream = new stream.PassThrough();
bufferStream.end(Buffer.from(req.body.base64Image, 'base64'));

更多关于decoding base64creating the stream.

然后我们将通过管道将流传输到由file.createWriteStream函数创建的写流中.

var gcs = require('@google-cloud/storage')({
  projectId: 'grape-spaceship-123',
  keyFilename: '/path/to/keyfile.json'
});

//Define bucket.
var myBucket = gcs.bucket('my-bucket');
//Define file & file name.
var file = myBucket.file('my-file.jpg');
//Pipe the 'bufferStream' into a 'file.createWriteStream' method.
bufferStream.pipe(file.createWriteStream({
    metadata: {
      contentType: 'image/jpeg',
      metadata: {
        custom: 'metadata'
      }
    },
    public: true,
    validation: "md5"
  }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

有关file.createWriteStreamFile docsbucket.uploadbucket.upload method code in the Node SDK的信息.

因此,上述代码的工作方式是定义要将文件放入的bucket,然后定义文件和文件名.我们不在这里设置上传选项.然后,我们将刚刚创建的bufferStream变量导入到前面讨论的file.createWriteStream方法中.在这些选项中,我们定义了元数据和其他要实现的选项.直接查看Node code on Github,找出它们是如何分解bucket.upload函数的,这非常有帮助,并建议您也这样做.最后,我们附加了几个事件,用于记录上传何时完成以及何时出错.

Node.js相关问答推荐

MongoServelSelection错误:服务器 Select 在30000 ms后超时

错误:找不到模块';/var/apps/前端/bash';

使用NodeJS输出检索Base64图像的网络报废

使用HTTPS从NodeJS 17.9.1升级到18.0.0后,SignalR连接失败

如何使用NodeJS处理来自请求的单个或多个文件?

如何在RavenDB中执行JS索引?

创建查询以展开数组并筛选出具有特定值的元素之后的元素

无法截取页面截图

将 express js app.use() 移动到另一个文件

Express.js - 监听请求中止

如何让 vscode 假设一个 node.js 上下文,以便它不假设 `fetch` 存在?

FirebaseCloudMessaging : PlatformException (PlatformException(null-error, Host platform returned null value for non-null return value., null, null))

我怎样才能让`git`失败而不是要求提供凭据

Aptana Studio 是否有 NodeJS 插件?

如何在 Node.js 的 console.log() 中创建换行符

如何获取在 NodeJS 中执行的脚本的文件名?

node.js 是否支持yields ?

所有的javascript回调都是异步的吗?如果不是,我怎么知道哪些是?

npm publish 导致'错误:EPERM:不允许操作,取消链接...',errno -4048

- configuration.output.path:提供的值public不是绝对路径!使用 Webpack