javascript - 将 jpg 上传到 Firebase 存储不会完全上传文件
问题描述
我正在尝试编写一个函数,将 jpeg 图像上传到 firebase 存储并返回上传文件的下载链接。但是当我执行该函数时,文件并没有完全上传到存储中,即原始文件大小为 10 KB,上传文件大小为 9 B。我正在使用以下代码:
const storageRef = firebase.storage().ref();
const dpRef = storageRef.child("users/dp.jpg").put(file, {
contentType: "image/jpeg",
});
dpRef.on(
firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log("Upload is paused");
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log("Upload is running");
console.log(progress);
break;
default:
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case "storage/unauthorized":
// User doesn't have permission to access the object
console.log("Unauthorized");
break;
case "storage/canceled":
// User canceled the upload
console.log("Cancelled");
break;
// ...
case "storage/unknown":
// Unknown error occurred, inspect error.serverResponse
console.log("Unknown");
break;
default:
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
dpRef.snapshot.ref.getDownloadURL().then((downloadURL) => {
console.log("File available at", downloadURL);
});
}
);
console.log(progress)
出于某种原因,显示 NaN 。我也试过下载
解决方案
我不确定是什么问题,但我最近这样做了,我可以分享我的代码:
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/storage';
const uploadImageFetch = async (uri) => {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
console.log(e);
reject(new TypeError('Network request failed'));
};
xhr.responseType = 'blob';
xhr.open('GET', uri, true);
xhr.send(null);
});
const imageNameBefore = uri.split('/');
const imageName = imageNameBefore[imageNameBefore.length - 1];
const ref = firebase.storage().ref().child(`images/${imageName}`);
const snapshot = await ref.put(blob);
blob.close();
return await snapshot.ref.getDownloadURL();
};
此函数接受带有图像的本地 URI,并返回下载 URL。您可以在官方文档https://firebase.google.com/docs/storage/web/upload-files中查看更多示例
推荐阅读
- go - 当数组在 Golang 中设置为 nil 时 gc 会收集对象吗?
- node.js - 如何在循环中调用后续回调?
- c - 链表 C 中的分段错误
- swift - 如何从包含#开头和结尾没有空格的字符串中获取主题标签?
- java - 连接来自多个数据库的表
- ios - 使用 xcode 10 后 Xcode 9 找不到资产
- c# - 无法加载文件或程序集“Microsoft.VisualStudio.Diagnostics.PerformanceProvider,版本=14.0.0.0
- java - 数组java中的最小值
- javascript - 通过 vue 和 electron 共享一个全局变量
- python - 如何在已知变量的情况下数值求解多变量联立方程?