Upload an object
We pick a name for the object and build a storage reference with it. If it matches an existing object, the upload will overwrite it.
We call uploadBytes()
or put()
with such reference and a File or Blob object.
// client
uploadBytes(ref, file).then((snapshot) => {})
// admin
ref.put(file).then((snapshot) => {}
getting a File or Blob in the browser
input file element
<input onChange={handleFiles} type="file" />
<button onClick={uploadFile}>Upload</button>
get the file from the input
function handleFiles(event) {
const files = event.target.files
const firstFile = files[0]
setUploadFile(firstFile)
}
working with the upload task
we may track the upload progress, and download the object once it's uploaded.
function uploadFile() {
const uploadFileRef = publicStorageRef.child(uploadfile.name)
const uploadTask = uploadFileRef.put(uploadfile)
uploadTask.on(
"state_changed",
function (snapshot) {
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
console.log("Upload is " + progress + "% done")
setProgress(progress)
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:
break
}
},
function (error) {
// Handle unsuccessful uploads
},
function () {
// Handle successful uploads on complete
// get the URL of the uploaded file
uploadTask.snapshot.ref.getDownloadURL().then(function (downloadURL) {
console.log("File available at", downloadURL)
})
}
)
}