【问题标题】:When trying to upload an image within my React App, the code does not work尝试在我的 React 应用程序中上传图片时,代码不起作用
【发布时间】:2022-11-22 23:14:50
【问题描述】:

我正在使用 Firebase 来存储图像。我遵循了 Firebase 文档,但它不起作用。 uploadImageFile 开始,正如我看到的“图像上传开始”,但控制台只显示上传已完成 0%,并且不会继续进行。

此外,在 uploadImageFile 开始运行之前会有延迟。

  const [imageFile, setImageFile] = useState("")
  const [percentage, setPercentage] = useState(null)
  const [data, setData] = useState({})
  const [progress, setProgress] = useState(0)


  useEffect(() => {
    const name = imageFile.name
    const storageRef = ref(storage, `website images/${name}`)
    const uploadTask = uploadBytesResumable(storageRef, imageFile)

    const uploadImageFile = () => {
      console.log("image upload started")
      setShowInfo1(false)
      uploadTask.on('state_changed', 
        (snapshot) => {
          const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log('Upload is ' + progress + '% done');
          setPercentage(progress)
          switch (snapshot.state) {
            case 'paused':
              console.log('Upload is paused');
              break;
            case 'running':
              console.log('Upload is running');
              break;
            default:
              break;
          }
        }, 
        (error) => {console.log(error)}, 
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
            console.log("done")
            setData((prev) => ({...prev, img:downloadURL}))      
          });
        }
      );
    }
    imageFile && uploadImageFile() 
  }, [imageFile])

输入SN-P:

<label htmlFor="websiteImageUpload">upload images</label>
<input type="file" id="websiteImageUpload" onChange={(e) => setImageFile(e.target.files[0])} style={{ display: "none"}} required></input>

【问题讨论】:

  • 是否有任何错误记录到控制台?

标签: reactjs firebase firebase-storage


【解决方案1】:

存储设置是否打开读写?

如果是这样 - 我仍然附上一个代码,它只在 java 中做同样的事情。 我希望这能帮到您。

private void uploadDataToFireBase(Uri imageUri, String desc, String price) {
    StorageReference storageReference = FirebaseStorage.getInstance().getReference("upload");
    final String randomUUid = UUID.randomUUID().toString();
    String imageName = randomUUid + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(getContentResolver().getType(imageUri));
    final StorageReference imageRef = storageReference.child(imageName);
    UploadTask uploadTask = imageRef.putFile(imageUri);
    uploadTask.continueWithTask(task -> imageRef.getDownloadUrl()).addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            Map<String, String> itemMap = new HashMap<>();
            itemMap.put("desc", desc);
            itemMap.put("toSwitch", mSwitchEditText.getText().toString());
            itemMap.put("price", price);
            itemMap.put("imageItem", task.getResult().toString());
            mDbUser.child(FirebaseAuth.getInstance().getUid()).child("items").child(randomUUid).setValue(itemMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    if (task.isSuccessful()) {
                        Toast.makeText(ItemActivity.this, "Item uploaded", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        handleProgressBar(false);
                        Toast.makeText(ItemActivity.this, "Failed to upload", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }
    });
}

【讨论】:

    猜你喜欢
    • 2013-03-13
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 2018-11-22
    • 2013-10-24
    • 2021-01-20
    • 2021-03-11
    • 2020-12-25
    相关资源
    最近更新 更多