如何使用Node.js将内存中的文件数据上传到Google云存储?

如何使用Node.js将内存中的文件数据上传到Google云存储?

问题描述:

我正在从URL中读取图像并进行处理.我需要将此数据上传到云存储中的文件,当前我正在将数据写入文件并上传此文件,然后删除此文件.有什么方法可以将数据直接上传到云存储中?

I am reading an image from a url and processing it. I need to upload this data to a file in cloud storage, currently i am writing the data to a file and uploading this file and then deleting this file. Is there a way i can upload the data directly to the cloud stoage?

static async uploadDataToCloudStorage(rc : RunContextServer, bucket : string, path : string, data : any, mimeVal : string | false) : Promise<string> {
if(!mimeVal) return ''

const extension = mime.extension(mimeVal),
      filename  = await this.getFileName(rc, bucket, extension, path),
      modPath   = (path) ? (path + '/') : '',
      res       = await fs.writeFileSync(`/tmp/${filename}.${extension}`, data, 'binary'),
      fileUrl   = await this.upload(rc, bucket, 
                            `/tmp/${filename}.${extension}`,
                            `${modPath}${filename}.${extension}`)

await fs.unlinkSync(`/tmp/${filename}.${extension}`)

return fileUrl
}

static async upload(rc : RunContextServer, bucketName: string, filePath : string, destination : string) : Promise<string> {
const bucket : any = cloudStorage.bucket(bucketName),
      data   : any = await bucket.upload(filePath, {destination})

return data[0].metadata.name
}

使用节点流可以上传数据而无需写入文件.

The data can be uploaded without writing to a file by using nodes streams.

const stream     = require('stream'),
      dataStream = new stream.PassThrough(),
      gcFile     = cloudStorage.bucket(bucketName).file(fileName)

dataStream.push('content-to-upload')
dataStream.push(null)

await new Promise((resolve, reject) => {
  dataStream.pipe(gcFile.createWriteStream({
    resumable  : false,
    validation : false,
    metadata   : {'Cache-Control': 'public, max-age=31536000'}
  }))
  .on('error', (error : Error) => { 
    reject(error) 
  })
  .on('finish', () => { 
    resolve(true)
  })
})