繁体   English   中英

我正在尝试上传图片,但图片没有添加到云 Firestore,它上传到了 Firebase 存储但没有显示在 React 应用程序中

[英]I'm trying to upload image but image is not adding to cloud firestore, its uploaded on firebase storage But not showing in React app

这是在 React 应用上上传图片的代码。 它显示在 Firebase 存储上,但未添加到云 Firestore 中。 这就是为什么我无法在 React 应用程序上手动上传任何图像。 我用谷歌搜索了很多次,但无法解决这个问题。

function  Imgupload({username}){

**strong text**    const [caption,setCaption]=useState('');
    const [image,setImage]=useState(null);
    //const [url,setUrl]= useState("");
    const [progress,setProgress]=useState(0);

    const handlechange = (e)=>{
       if(e.target.files[0]){
           setImage(e.target.files[0]);
       } 
    };

    const handleUpload = () =>{
      const uploadTask= storage.ref('images/$ {image.name}').put(image);
      
        uploadTask.on(
         "state_change",
         (snapshot) =>{
             //progress function..
         const progress=Math.round(
            (snapshot.bytesTransferred/snapshot.totalBytes) * 100
            );
            setProgress(progress);
         },
         (error) =>{            //error func..
            console.log(error);
             alert(error.message);
         },
         ()=>{ //complete func..
           storage
           .ref("images") 
           .child(image.name)
           .getDownloadURL()
           .then (url =>{
        //post img on db..
          db.collection("posts").add({
            timestamp:firebase.firestore.FieldValue.serverTimestamp(),
            caption  :caption,
            imgurl   :url,
            username :username   
        });
           setProgress(0);
            setCaption("");
            setImage(null);
           });
         }
      );
    }

这是来自控制台的错误:

localhost/:1 Uncaught (in promise) FirebaseError: Firebase Storage: Object 'images/Screenshot (202).png' does not exist. (storage/object-not-found)
{
  "error": {
    "code": 404,
    "message": "Not Found."`enter code here`
  }
}

无法解决这个问题。 请帮忙。

此处的文件名中有一个额外的空格:

const uploadTask= storage.ref('images/$ {image.name}').put(image);
                                    // 👆

当您在此处调用getDownloadURL时,您没有相同的空间:

storage
 .ref("images") 
 .child(image.name)
 .getDownloadURL()

所以这两个代码片段指向不同的文件,这就解释了为什么第二个片段找不到你上传的文件。


我建议使用单个变量来保存引用,并在两个片段中使用它:

const imageRef = storage
 .ref("images") 
 .child(image.name);
const uploadTask= imageRef.put(image);

...

imageRef.getDownloadURL()...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM