在JavaScript中将文件路径转换为文件对象
我想使用JavaScript在firebase上上载文件我的服务器上的文件,并且还有文件路径,但firebase不允许从文件路径上载文件,它显示以下错误消息:在JavaScript中将文件路径转换为文件对象,javascript,jquery,ajax,Javascript,Jquery,Ajax,我想使用JavaScript在firebase上上载文件我的服务器上的文件,并且还有文件路径,但firebase不允许从文件路径上载文件,它显示以下错误消息: code\“存储/无效参数” 消息:“Firebase存储:索引0处的'put'中的参数无效:应为Blob或文件。” 名称:“FirebaseError” 服务器响应:空 如何上载文件或将文件路径转换为文件对象?您可以使用此功能在firebase中上载文件。uri是进一步创建firebase所需文件类型的文件路径 const up
code\“存储/无效参数”
消息:“Firebase存储:索引0处的'put'中的参数无效:应为Blob或文件。”
名称:“FirebaseError”
服务器响应:空
如何上载文件或将文件路径转换为文件对象?您可以使用此功能在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)
}
}