javascript - 在 JavaScript 中将文件路径转换为文件对象
问题描述
我想使用 JavaScript 将文件上传到 firebase 我的服务器上的文件,并且还有文件路径,但 firebase 不允许从文件路径上传文件,它显示以下错误消息:
code_: "storage/invalid-argument"
message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."
name_: "FirebaseError"
serverResponse_: null
如何上传文件或将文件路径转换为文件对象?
解决方案
您可以使用此功能在 Firebase 中上传文件。uri 是进一步创建 firebase 所需文件类型的文件路径。
const uploadImage = async (uri) => {
const uniqid = () => Math.random().toString(36).substr(2, 9);
const ext = uri.split('.').pop(); // Extract image extension
const filename = `${uniqid()}.${ext}`; // Generate unique name
const ref = fb.storage().ref().child(`images/${filename}`);
const response = await fetch(uri);
// const blob = await response.blob();
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 snapshot = await ref.put(blob);
blob.close();
const imgUrl = await snapshot.ref.getDownloadURL();
return imgUrl;
}
在此函数之后,您可以调用此函数将您的图像上传到 Firebase 数据库中,如下所示,
const formSubmit= async(values, action)=>{
console.log(values);
try{
uploadImage(image) //this is my image upload code
.then( async(res) => {
setLoader(false);
var user = fb.auth().currentUser;
await user.updateProfile({
displayName: values.name,
photoURL: res // use the response url to store in mapped data table
}).then(function(res) {
console.log(res)
}).catch(function(error) {
console.log(error)
});
})
.catch(error => {
console.log('it does not work')
console.error(error)
})
}catch(error){
console.log(error)
}
}
推荐阅读
- python - 如何读取变量的名称python
- javascript - 在mac上运行离子应用程序时出错
- ruby - 如何在 Ruby 中捕获窗口屏幕截图
- java - 案例中如何使用涉及实例化的switch语句?
- node.js - 在节点 js 中找不到“nd sampleApp”命令
- javascript - 解析器(js)的正则表达式lookbehind替代
- python - 在 for 循环中生成时识别按钮
- puppet - puppet 资源如何在不编译失败的情况下检查 puppetmaster 上的数据源?
- c# - C#如何从IEnumerable中创建一个列表
- google-chrome-extension - Chrome 扩展错误:拒绝执行内联事件处理程序