Skip to content

Instantly share code, notes, and snippets.

@afk-mario
Created September 16, 2019 07:06
Show Gist options
  • Save afk-mario/159439da7f2bf304630b7d8e1b08ee0e to your computer and use it in GitHub Desktop.
Save afk-mario/159439da7f2bf304630b7d8e1b08ee0e to your computer and use it in GitHub Desktop.
rc-upload & firebase
const customUpload = async ({ file, uploadTo, onProgress, onError, onSuccess }) => {
const storage = firebase.storage();
try {
const storageRef = await storage.ref();
const uploadFile = storageRef.child(`${uploadTo}/${file.name}`);
const uploadTask = uploadFile.put(file);
uploadTask.on(
"state_changed",
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
const percent = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
).toFixed(2);
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
onProgress({ percent }, file);
break;
default:
break;
}
},
error => {
// Handle unsuccessful uploads
onError(error, file);
},
() => {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
onSuccess(downloadURL, file);
});
}
);
} catch (e) {
console.error(e);
onError(e);
}
};
const FirebaseUpload = ({ className, uploadTo, children, ...rest }) => {
const customRequest = e => {
customUpload({ ...e, uploadTo });
};
return (
<Upload
beforeUpload={beforeUpload}
customRequest={customRequest}
{...rest}
>
<div className={className}>{children}</div>
</Upload>
);
};
FirebaseUpload.propTypes = {
uploadTo: PropTypes.string.isRequired,
className: PropTypes.string,
children: PropTypes.node,
};
FirebaseUpload.defaultProps = {
className: undefined,
children: undefined,
};
const App = ({uploadTo, avatarURL, uploading}) => (
<FirebaseUpload
name="photoURL"
uploadTo={uploadTo}
>
{avatarURL ? (
<img src={avatarURL} alt="avatar" style={{ width: "100%" }} />
) : (
<div>
<Icon type={uploading ? "loading" : "plus"} />
<div>
{uploading ? "Uploading" : "Upload"}
</div>
</div>
)}
</FirebaseUpload>);
ReactDOM.render(
<App />,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment