如何在使用 Firebase 存储上传后获取调整大小的 downloadUrl

使用 Firebase Web SDK,我可以在上传文件后轻松获取 downloadUrl

const task = firebase.ref().child('myFolder').put(file, metadata)task.then(snapshot => {
 snapshot.ref.getDownloadURL()) }

但是我安装了调整大小的图像扩展,现在,我想尽快获得调整大小的 downloadUrl。怎么做 ?我没有找到任何关于它的解释......


明月笑刀无情
浏览 220回答 1
1回答

慕尼黑的夜晚无繁华

扩展名根据您的配置方式确定性地确定新文件名。您可以在扩展程序的源代码中查看如何确定名称的确切代码。当您安装扩展程序时,它会要求提供与原始路径相关的调整大小图像的路径。那是新图像的路径(当然,相对于原始图像)。除此之外,文档声明它将以配置的宽度和高度为后缀。使用与原始上传图像相同的名称命名调整大小的图像,但后缀为您指定的宽度和高度。因此,如果您没有指定路径,而是指定了 200x200,然后上传image.jpg到存储桶的根目录,则新名称将是:image_200x200.jpg,位于存储桶的根目录。如果您指定了 path&nbsp;resized,并且您指定了 200x200,并且上传image2.jpg到存储桶的根目录,则新名称将/resized/image2_200x200.jpg与源图像在同一个存储桶中。要获取下载 URL,您需要getDownloadURL在扩展函数创建新文件后调用具有新名称的存储引用。如果你想等待,你可以用类似下面的代码来轮询:function delay(t, v) {&nbsp; return new Promise(function(resolve) {&nbsp;&nbsp; &nbsp; setTimeout(resolve.bind(null, v), t)&nbsp; });}function keepTrying(triesRemaining, storageRef) {&nbsp; if (triesRemaining < 0) {&nbsp; &nbsp; return Promise.reject('out of tries');&nbsp; }&nbsp; return storageRef.getDownloadURL().then((url) => {&nbsp; &nbsp; return url;&nbsp; }).catch((error) => {&nbsp; &nbsp; switch (error.code) {&nbsp; &nbsp; &nbsp; case 'storage/object-not-found':&nbsp; &nbsp; &nbsp; &nbsp; return delay(2000).then(() => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return keepTrying(triesRemaining - 1, storageRef)&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; &nbsp; &nbsp; return Promise.reject(error);&nbsp; &nbsp; }&nbsp; })}这就是上传后的调用方式:const storageRef = firebase.storage().ref().child('image_200x200.jpg');keepTrying(10, storageRef).then((url) => console.log(url));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript