Skip to content

Instantly share code, notes, and snippets.

@Teepheh-Git
Last active September 5, 2023 14:16
Show Gist options
  • Save Teepheh-Git/1a63d344e46cf83d3fb0d8849c71dacc to your computer and use it in GitHub Desktop.
Save Teepheh-Git/1a63d344e46cf83d3fb0d8849c71dacc to your computer and use it in GitHub Desktop.
upload single img to cloudinary f
const [file, setFile] = useState<any>();
const [fileData, setFileData] = useState<any>();
const [fileDataArr, setFileDataArr] = useState<any>();
const [selectedFileData, setSelectedFileData] = useState<any[]>([]);
const [uploadProgress, setUploadProgress] = useState<string | null>(null);
const [currentFileIndex, setCurrentFileIndex] = useState<number | null>(null);
function handleChange(e: ChangeEvent<any>) {
let images: any[] = selectedImages;
let fileDatums: any[] = selectedFileData;
if (selectedImages.includes(URL.createObjectURL(e.target.files[0]))) return;
images.push(URL.createObjectURL(e.target.files[0]));
fileDatums.push(e.target.files[0]);
setSelectedImages(images);
// setSelectedImages(images.filter((v, i, s) => s.indexOf(v) === i));
setSelectedFileData(fileDatums);
setFile(URL.createObjectURL(e.target.files[0]));
setFileData(e.target.files[0]);
}
async function uploadImagesToCloudinary() {
if (!file) return;
//set index to know the position of the image being uploaded
setCurrentFileIndex(selectedImages.length - 1);
const { signature, timestamp, cloudName, apiKey, upload_preset, sec }: GetSignatureProps =
await axios
.get(`${BASE_URL}/upload/image-signature`, {
headers: { Authorization: `Bearer ${token}` },
})
.then(({ data }) => {
return {
apiKey: data?.data?.apiKey,
cloudName: data?.data?.cloudName,
signature: data?.data?.signature,
timestamp: data?.data?.timestamp,
upload_preset: data?.data?.upload_preset,
sec: data?.data?.sec,
};
});
const formData = new FormData();
formData.append("file", fileData);
// formData.append("upload_preset", upload_preset);
formData.append("cloud_name", cloudName);
formData.append("api_key", apiKey);
formData.append("timestamp", timestamp);
formData.append("signature", signature);
// formData.append("sec", sec);
return axios
.post(`https://api.cloudinary.com/v1_1/${cloudName}/upload`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
onUploadProgress: (progressEvent: any) => {
const progress = (progressEvent.loaded / progressEvent.total) * 100;
setUploadProgress(progress.toFixed(2));
},
})
.then(({ data }) => {
console.log(data, "pppp");
return { secure_url: data?.secure_url };
})
.finally(() => {
setUploadProgress(null);
setCurrentFileIndex(null);
});
}
<input
type="file"
id="image_uploads"
name="image_uploads"
accept=".jpg, .jpeg, .png, .webp"
multiple
style={{
opacity: "0",
position: "absolute",
width: "110px",
height: "110px",
cursor: "pointer",
}}
onChange={handleChange}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment