In this post we will upload Image from local to cloudinary. We will create useCloudinary hook that will take care of the stuff related to file upload.
Libraries
SolidJS
Axios
SUID
Shortid
Features
Image preview
Upload to Cloudinary
Progress bar
Abort image upload
src/hooks/useCloudinary.jsx
importaxiosfrom"axios";importshortidfrom"shortid";import{createStore}from"solid-js/store";consturl=`https://api.cloudinary.com/v1_1/${import.meta.env.VITE_CLOUDINARY_CLOUD_NAME}/image/upload`;exportdefaultfunctionuseCloudinary(){const[store,setStore]=createStore({image:null,imagePreview:"",uploadProgress:0,alert:null,abortToken:null,});functionhandleImageChange(e){constimage=e.target.files[0];// create blob url of selected image for previewconstimagePreview=URL.createObjectURL(image);// create axios cancellation token to abort request in futureconstabortToken=axios.CancelToken.source();setStore("image",image);setStore("imagePreview",imagePreview);setStore("abortToken",abortToken);setStore("alert",{severity:"success",text:"Image loaded successfully",});}functionhandleImageRemove(){// cleanup blob metadataURL.revokeObjectURL(store.imagePreview);window.location.reload();}asyncfunctionhandleImageUpload(){try{constformData=newFormData();formData.append("file",store.image);formData.append("upload_preset",import.meta.env.VITE_CLOUDINARY_UPLOAD_PRESET);formData.append("api_key",import.meta.env.VITE_CLOUDINARY_API_KEY);formData.append("public_id",shortid.generate());constresponse=awaitaxios.post(url,formData,{onUploadProgress:handleUploadProgess,cancelToken:store.abortToken.token,});setStore("alert",{severity:"success",text:"Image uploaded to cloudinary successfully",});// revoke preview blob urlURL.revokeObjectURL(store.imagePreview);setStore("imagePreview",response.data.url);}catch (error){console.log(error);}}functionhandleUploadProgess(progressEv){constprogress=Math.floor((progressEv.loaded/store.image.size)*100);console.log(progress);setStore("uploadProgress",progress);}functionhandleCancelUpload(){store.abortToken.cancel();setStore("alert",{severity:"error",text:"Image upload aborted",});}return{store,handleImageChange,handleImageRemove,handleImageUpload,handleCancelUpload,};}
we have created a new store and initialise with initial value.
image field will store image selected from local.
imagePreview field will store image url for image preview
and cloudinary url after successfully uploaded.
uploadProgress field will show percentage of image data
uploaded to cloudinary.
alert show success, error and warning message.
abortToken field will store Axios CancelTokenSource which
help to abort request in middle.
handleImageChange() function create blob url of image for
preview and axios cancellation token which we can use in
future to cancel request in middle.
handleImageRemove() method remove preview image and revoke
blob url to clean memory acquired by blob metadata.
handleImageUpload() function upload image to cloudinary
using axios post request and when image successfully
uploaded it revoke blob url and show image from cloudinary
url.
handleUploadProgess() function track uploaded chunk of
image data.
handleCancelUpload() function cancel axios request.
Create .env file in project root and add required environment variable.
Those templates dependencies are maintained via pnpm via pnpm up -Lri.
This is the reason you see a pnpm-lock.yaml. That being said, any package manager will work. This file can be safely be removed once you clone a template.