【问题标题】:Upload image to firebase storage from React Dropzone (gives invalid Image)从 React Dropzone 将图像上传到 Firebase 存储(提供无效图像)
【发布时间】:2022-01-26 20:12:19
【问题描述】:

我正在使用 React Dropzone 将文件从 React 上传到 firebase,如下所示:

const onDrop = useCallback((acceptedFiles, fileRejections) => {
    //Check if file type is image
    //Check if file size < 5MB
    //Upload
    if (fileRejections.length > 0) {
      setError(true);
    } else setError(false);
    if (acceptedFiles.length > 0) {
      const file = acceptedFiles[0];
      console.log(file);
      setFile({
        ...file,
        preview: URL.createObjectURL(file),
      });
      setFileUploaded(true);
    }
  }, []);

这是我的上传处理程序:


  const handleImageUpload = () => {
    //Upload Image to Firebase
    //Check if file exists
    if (file !== null || file !== undefined) {
      const storageRef = ref(
        Client.storage,
        `/db-dev/user-metadata/portfolio/images/first-image.jpg`
      );
      console.log('Process begins');
      uploadBytes(storageRef, file).then((snapshot) => {
        console.log('Uploaded a blob or file!');
      });
    }
  };

这两件事确实有效,但我相信由于某种原因它们没有像在 firebase 存储文件夹中那样对图像进行编码或解码,我将图像视为无效图像。

有人可以帮助我了解哪里出了问题吗? (为了确保文件正确加载,我还使用:preview: URL.createObjectURL(file), 查看文件,它在浏览器中正确加载。

对于文件上传,我正在关注最新的 firebase documentation

它将文件类型设置为octet-stream 不确定这意味着什么:

编辑 1: 我尝试将元数据设置为 image/jpeg:

uploadBytes(storageRef, file, {
        contentType: 'image/jpeg',
      }).then((snapshot) => {
        console.log('Uploaded a blob or file!');
      });

但现在它显示:

【问题讨论】:

    标签: firebase-storage react-dropzone


    【解决方案1】:

    问题出在这一步:

    setFile({
            ...file,
            preview: URL.createObjectURL(file),
          });
    

    由于某种原因,它没有正确传播。我把它改成:

    setFile({
            file:file,
            preview: URL.createObjectURL(file),
          });
    

    以及上传功能到:

    const handleImageUpload = () => {
        //Upload Image to Firebase
        //Check if file exists
        if (file !== null || file !== undefined) {
          const storageRef = ref(
            Client.storage,
            `/db-dev/user-metadata/portfolio/images/first-image.jpg`
          );
    
          console.log('Process begins');
          uploadBytes(storageRef, file.file, {
            contentType: file.file.type,
          }).then((snapshot) => {
            console.log('Uploaded a blob or file!');
          });
        }
      };
    

    然后它工作正常。虽然这对我来说是一件非常愚蠢的事情,但希望这对将来的人有所帮助

    【讨论】:

      猜你喜欢
      • 2020-03-06
      • 1970-01-01
      • 2017-09-25
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多