首页 > 解决方案 > 在 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

如何上传文件或将文件路径转换为文件对象?

标签: javascriptjqueryajax

解决方案


您可以使用此功能在 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)
     }
}

推荐阅读