如何使用 node.js 中的文件 url 从 firebase 中删除文件?
要从 firebase 存储中删除文件,我们需要一个引用来将文件存储在存储中。由于我们只有文件 URL,我们需要在 firebase 存储中创建文件的引用对象,然后删除该文件。
使用文件 URL 删除文件可以分两步完成 -
- 使用 firebase.storage 中的 refFromUrl 方法获取对存储的引用。
- 使用从步骤 1 获得的存储中文件的引用删除文件。
refFromUrl方法返回对该文件的引用,并且可以将两种类型的文件 URL 作为输入:
- gs:// 网址,例如 gs://bucket/files/image.png
- 从对象元数据中获取的下载 URL。
示例 1:使用 refFromURL 方法从给定文件 URL 中删除文件。
Javascript
var fileUrl =
'https://firebasestorage.googleapis.com/b/bucket/o/images%20geeksforgeeks.jpg';
// Create a reference to the file to delete
var fileRef = storage.refFromURL(fileUrl);
console.log("File in database before delete exists : "
+ fileRef.exists())
// Delete the file using the delete() method
fileRef.delete().then(function () {
// File deleted successfully
console.log("File Deleted")
}).catch(function (error) {
// Some Error occurred
});
console.log("File in database after delete exists : "
+ fileRef.exists())
Javascript
// gs Bucket URL
var fileUrl = 'gs://bucket/geeksforgeeks/image.png';
// Create a reference to the file to delete
var fileRef = storage.refFromURL(fileUrl);
console.log("File in database before delete exists : "
+ fileRef.exists())
// Delete the file using the delete() method
fileRef.delete().then(function () {
// File deleted successfully
console.log("File Deleted")
}).catch(function (error) {
// Some Error occurred
});
console.log("File in database after delete exists : "
+ fileRef.exists())
输出:
File in database before delete exists : true
File Deleted
File in database after delete exists : false
示例 2:使用存储桶 gs:// URL 删除文件
Javascript
// gs Bucket URL
var fileUrl = 'gs://bucket/geeksforgeeks/image.png';
// Create a reference to the file to delete
var fileRef = storage.refFromURL(fileUrl);
console.log("File in database before delete exists : "
+ fileRef.exists())
// Delete the file using the delete() method
fileRef.delete().then(function () {
// File deleted successfully
console.log("File Deleted")
}).catch(function (error) {
// Some Error occurred
});
console.log("File in database after delete exists : "
+ fileRef.exists())
输出 :
File in database before delete exists : true
File Deleted
File in database after delete exists : false