Firebase功能会更改存储中上传文件的fileName

时间:2017-08-22 14:28:05

标签: javascript firebase google-cloud-functions

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

我正在使用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) {
});
//////////////////////////////////////////////////////////////
});

1 个答案:

答案 0 :(得分:3)

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