2017-07-06 41 views
2

我正在从一个URL中读取图像并对其进行处理。我需要将这些数据上传到云存储中的文件,目前我正在将数据写入文件并上传此文件,然后删除此文件。有没有办法将数据直接上传到云端存储?如何使用nodejs将内存中的文件数据上传到谷歌云存储?

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 
} 
+0

你有没有找到办法做到这一点?我也想用JSON数据做同样的事情。 – Peza

+0

我发布了我使用的解决方案,对于延迟抱歉。 –

回答

0

通过使用节点流,可以在不写入文件的情况下上载数据。

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) 
    }) 
}) 
相关问题