简体   繁体   English

尝试将图像上传到 Firebase 存储时出错

[英]Error when trying to upload images to Firebase storage

I am trying to create an app which allow the user to upload an image and display it in the page with React and Firebase.我正在尝试创建一个应用程序,允许用户上传图像并使用 React 和 Firebase 在页面中显示它。

this is the part of the code that responsible for the issue: the image variable is coming from from the state这是导致问题的代码部分:图像变量来自 state

const [image, setImage] = useState("");
const [caption, setCaption] = useState("");
const [progress, setProgress] = useState(0)

function handleChange (e){
    if  (e.target.files[0]){
        setImage(e.target.files[0]);
    }
}
function handleUpload(){
    const uploadTask =  storage.ref('images/${image.name}').put(image)
    uploadTask.on(
        "state_changed",
        (snapshot) => {
            const progress = Math.round(
            (snapshot.bytesTransferred / snapshot.totalBytes) *  100
             );
            setProgress(progress);

           },
           (error) => {
            console.log(error);
            alert(error.message);
            },
            () => {
                storage
                .ref("images")
                .child(image.name)
                .getDownloadURL()
                .then(url => {
                    db.collection("posts").add({
                        timestamp: db.FieldValue.serverTimestamp(),
                        caption : caption,
                        imgUrl: url,
                        userName: username
                    })
                            setProgress(0);
                            setCaption("");
                            setImage(null);
                })
            }

        )
  
}

and this error get logged in the console:并且此错误记录在控制台中:

Uncaught 

FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse_: null, name_: "FirebaseError"}code_: "storage/invalid-argument"message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."name_: "FirebaseError"serverResponse_: nullcode: (...)message: (...)name: (...)serverResponse: (...)__proto__: Object
    rethrowCaughtError @ react-dom.development.js:328
    runEventsInBatch @ react-dom.development.js:3336
    runExtractedPluginEventsInBatch @ react-dom.development.js:3537
    handleTopLevel @ react-dom.development.js:3581
    batchedEventUpdates$1 @ react-dom.development.js:21729
    batchedEventUpdates @ react-dom.development.js:798
    dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3591
    attemptToDispatchEvent @ react-dom.development.js:4311
    dispatchEvent @ react-dom.development.js:4232
    unstable_runWithPriority @ scheduler.development.js:659
    runWithPriority$1 @ react-dom.development.js:11077
    discreteUpdates$1 @ react-dom.development.js:21746
    discreteUpdates @ react-dom.development.js:811
    dispatchDiscreteEvent @ react-dom.development.js:4211

I have tried to change put(image) to put(blob) but it did not work我试图将put(image)更改为put(blob)但它没有用

  1. The line:该行:
const uploadTask =  storage.ref('images/${image.name}').put(image)

Has an error, it should be using the symbol ` (backquote/backtick) instead of using single quotes ' :有错误,它应该使用符号` (反引号/反引号)而不是使用单引号'

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

otherwise you will create a reference to the literal string images/${image.name} instead of image/value_of_variable_image.jpg more about Template literals can be found here否则,您将创建对文字字符串images/${image.name}的引用,而不是image/value_of_variable_image.jpg可以在此处找到有关模板文字的更多信息

  1. You haven't still showed us what's the content of the image variable, I can see from the code that you're calling a setState inside a function that appears to be a callback, but I'm not seeing from where are you calling, you can do it from a input like this:你还没有告诉我们image变量的内容是什么,我从代码中可以看出你在 function 中调用了一个setState似乎是一个回调,但我没有看到你在哪里调用,你可以从这样的输入中做到这一点:
<input type="file" onChange={handleChange} />

If you're already using it like that, I recommend to add console.log(image) outside of a function in order debug what's the content of the variable before sending it to put() .如果您已经在使用它,我建议在 function 之外添加console.log(image)以便在将变量发送到put()之前调试变量的内容。 Just as a reference the output from the console.log(image) should be an instance of the File javascript API作为参考,来自console.log(image)的 output 应该是File javascript API的一个实例

暂无
暂无

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

相关问题 异步/等待:尝试访问填充了从 firebase 存储中下载的图像的数组时出现“超出范围错误” - Async/Await: "out of range error" when trying to access array filled with downloaded images from firebase storage 上传多张图片到Firebase存储得到url张 - Get url of multi images when upload them to Firebase Storage Angular Error not allowing me to update and upload images in my Firebase Storage 找不到存储桶的原因 - Angular Error not allowing me to update and upload images in my Firebase Storage cause of not finding storage bucket Firebase function 尝试写入 firebase 存储“Firebase 存储:用户无权访问”时出错 - Firebase function getting error when trying to write to firebase storage "Firebase Storage: User does not have permission to access" 如何上传SVG张图片到firebase存储? - How to upload SVG images on firebase storage? 当我尝试在 firebase 存储上导入文件时出现错误 - im getting error when im trying to import file on firebase storage 尝试将图像上传到 firebase (Swift) 时出错 - Getting an error when trying to upload image to firebase (Swift) 尝试使用本机反应将图像上传到 firebase 存储时,应用程序在 iOS 上崩溃 - App crashes on iOS when trying to upload image to firebase storage using react native Firebase 云存储上传文件路径错误 - Firebase Cloud Storage Upload File Path Error Firebase storage-resize-images 未由存储桶上传触发 - Firebase storage-resize-images not triggered by bucket upload
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM