Alex Ironside
Alex Ironside

Reputation: 5059

Uploading files to Firebase using React

I'm trying to upload a file to Firebase like so:

uploadImage(file) {
    // Create the file metadata
    var metadata = {
        contentType: 'image/jpeg'
    };
    console.log(1);
    try {
        var uploadTask = firebase.storage().ref().child('images/' + file.name).put(file, metadata);
    } catch (e) {
        console.log('tutej', e)
    }
    // Upload file and metadata to the object 'images/mountains.jpg'
    console.log(2);
    // Listen for state changes, errors, and completion of the upload.
    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
        function (snapshot) {
            console.log(3);
            // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
            var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
            switch (snapshot.state) {
                case firebase.storage.TaskState.PAUSED: // or 'paused'
                    console.log('Upload is paused');
                    break;
                case firebase.storage.TaskState.RUNNING: // or 'running'
                    console.log('Upload is running');
                    break;
                default:
                    console.log('test1');
                    break;
            }
        }, function (error) {
            console.log(4);
            // A full list of error codes is available at
            // https://firebase.google.com/docs/storage/web/handle-errors
            switch (error.code) {
                case 'storage/unauthorized':
                    // User doesn't have permission to access the object
                    break;

                case 'storage/canceled':
                    // User canceled the upload
                    break;

                case 'storage/unknown':
                    // Unknown error occurred, inspect error.serverResponse
                    break;

                default:
                    console.log('test2');
                    break;
            }
        }, function () {
            console.log(4);
            // Upload completed successfully, now we can get the download URL
            uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
                console.log('File available at', downloadURL);
            });
        });
}

HTML:

<form encType="multipart/form-data" onSubmit={this.handleSubmit}>
    <textarea name="textAnswer" id="textAnswer" style={{
        width: '100%',
        height: '50vh',
        background: 'white',
        color: 'black'
    }}/>
    <input id="fileAnswer" type="file" size='10000000'/>
    <Button type='submit' style={{display: 'block'}}>Wyslij odpowiedz</Button>
    <Button onClick={this.handleClick} style={{display: 'block'}}>Anuluj rozwiazywanie</Button>
</form>

function call:

var fileAnswer = document.getElementById('fileAnswer').value;

if (fileAnswer.length > 0) {
    this.uploadImage(fileAnswer);
}

How it's supposed to work: I want the file uploaded with the HTML <input> element to be uploaded to Firebase, as a picture. So far when I try to do it I get this:

error = {
    code_: "storage/invalid-argument",
    message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.",
    name_: "FirebaseError",
    serverResponse_: null ,
};

From what I researched I need to make it into a Blob. But why? Is the value of the <input> field not a file? It looked like a path to the file. (example: C:\fakepath\8a25f4e0b058f2ce8480ef3741823762.png)

So what is the difference and how do I make it a file?

In short? What do I have to do to actually upload it, and why using <input> not enough?

Upvotes: 0

Views: 3894

Answers (1)

Alex Ironside
Alex Ironside

Reputation: 5059

Ok I recommend reading this tutorial. The uploadFile() method worked perfectly well.

Upvotes: 1

Related Questions