javascript - Firebase 函数更改存储中上传文件的文件名

标签 javascript firebase google-cloud-functions

有没有办法使用 Firebase 功能更改图像的文件名,而无需再次下载和上传?

我使用 onChange Listener 来捕获实际上传,并且获得了有关已上传文件所需的所有数据,但如果不下载它,我无法更改任何信息。

我当前的代码:

const functions = require('firebase-functions');
const path = require('path');

exports.addTimeStamp = functions.storage.object().onChange(event => {
const object = event.data; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.

// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return;
}

if (!filePath.startsWith('deliveryNote/')) {
    console.log('This is not a delivery note.');
    return;
}

// Get the file name.
const fileName = path.basename(filePath);
console.log('filename: ' + fileName);
// Exit if the image is already a thumbnail.
if (fileName.startsWith('note_')) {
    console.log('Already modified');
    return;
}

// Exit if this is a move or deletion event.
if (resourceState === 'not_exists') {
    console.log('This is a deletion event.');
    return;
}

// Exit if file exists but is not new and is only being triggered
// because of a metadata change.
if (resourceState === 'exists' && metageneration > 1) {
    console.log('This is a metadata change event.');
    return;
}

/////////////////////////////////////////////////////////////
//Added folowing code thx to Doug Stevenson
const bucket = gcs.bucket(object.bucket);
var file = bucket.file(filePath);
console.log('filepath: ' + filePath);
console.log('filename: ' + fileName);
const dirname = path.dirname(filePath);
file.move(dirname + '/' + 'note_' + fileName, function(err, destinationFile, apiResponse) {
});
//////////////////////////////////////////////////////////////
});

最佳答案

要与存储桶中的文件交互,您可以使用 Google Cloud Storage Node SDK 。使用它来获取表示更改的文件的 File 对象,并使用其 move方法更改其名称。

关于javascript - Firebase 函数更改存储中上传文件的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45820400/

相关文章:

javascript - Mongoose QueryStream 和请求模块

javascript - 处理一组顺序 bool 值

android - react Native Firebase 请求权限

swift - 我的代码如何知道 Firebase 何时完成检索数据?

node.js - Firebase createUserWithEmailAndPassword 方法在node.js 中未定义

firebase - 在 Cloud Functions for Firebase 中访问数据库数据

javascript - Iframe 下的 IE11 怪异模式 - javascript 错误

javascript - 在文本框中显示增值税值

python - 用于 python 输出数据文件的 GCP Cloud Functions

Firebase 部署错误 - 找不到模块 'firebase'