我正在从 url 读取图像并对其进行处理。我需要将这些数据上传到云存储中的一个文件,目前我正在将数据写入一个文件并上传这个文件,然后删除这个文件。有什么方法可以直接将数据上传到云端吗?
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
}
最佳答案
是的,可以使用 nodejs 从 URL 检索图像,对图像进行编辑,然后将其上传到 Google Cloud Storage(或 Firebase 存储),而无需在本地保存文件。
这是在 Akash 的回答的基础上构建的,具有对我有用的完整功能,包括图像处理步骤。
步骤
- 使用axios从远程 URL 检索图像流。
- 使用sharp对图像进行更改
- 使用Google Cloud Storage Library创建一个文件,并将图像数据保存到 Google Cloud Storage 中的文件中。 ( more node docs )
如果您是使用 firebase 存储的 firebase 用户,您仍然必须使用此库。用于存储的 firebase web 实现在 Node 中不起作用。如果您在 firebase 中创建了存储,您仍然可以通过 Google Cloud Storage Console 访问这一切.它们是同一回事。
const axios = require('axios');
const sharp = require('sharp');
const { Storage } = require('@google-cloud/storage');
const processImage = (imageUrl) => {
return new Promise((resolve, reject) => {
// Your Google Cloud Platform project ID
const projectId = '<project-id>';
// Creates a client
const storage = new Storage({
projectId: projectId,
});
// Configure axios to receive a response type of stream, and get a readableStream of the image from the specified URL
axios({
method:'get',
url: imageUrl,
responseType:'stream'
})
.then((response) => {
// Create the image manipulation function
var transformer = sharp()
.resize(300)
.jpeg();
gcFile = storage.bucket('<bucket-path>').file('my-file.jpg')
// Pipe the axios response data through the image transformer and to Google Cloud
response.data
.pipe(transformer)
.pipe(gcFile.createWriteStream({
resumable : false,
validation : false,
contentType: "auto",
metadata : {
'Cache-Control': 'public, max-age=31536000'}
}))
.on('error', (error) => {
reject(error)
})
.on('finish', () => {
resolve(true)
});
})
.catch(err => {
reject("Image transfer error. ", err);
});
})
}
processImage("<url-to-image>")
.then(res => {
console.log("Complete.", res);
})
.catch(err => {
console.log("Error", err);
});
关于node.js - 如何使用nodejs将内存文件数据上传到谷歌云存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44945376/