Last active
May 26, 2021 12:58
-
-
Save katendeglory/a287d0d311d1e5aa18a1af5b081190f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import Resizer from "react-image-file-resizer"; | |
import axios from "axios"; | |
const resize = Resizer.imageFileResizer; | |
let rawImgs; | |
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | |
/* | |
This function will be called multiple times if multiple files are uploaded, it takes a | |
file object from a form (the typical e.target.files[0]), and resizes it. | |
It will be used in the resizeImages function. | |
*/ | |
let resizeImage = (file) => { | |
return new Promise((resolve, reject) => { | |
resize( file, 500, 500, "JPEG", 100, 0, uri => resolve(uri), "blob" ); | |
}); | |
}; | |
/* | |
This function takes an array of files (the typical e.target.files array), resizes every files | |
and returns an array of resized files. it uses the function resizeImage defined above. | |
*/ | |
let resizeImages = async (files) => { | |
let resized = []; | |
for (let i = 0; i < files.length; i++) resized.push(await resizeImage(files[i])); | |
return resized; | |
}; | |
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | |
// we're going to use async await for a cleaner syntax | |
let onSubmit = async () => { | |
let formData = new FormData(); | |
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | |
// The raw images originally uploaded by the users are resized here | |
let resizedImgs = await resizeImages(rawImgs); | |
// Once the resize is done, we'll need to append the optimized files to the form data | |
resizedImgs.forEach((resizedImg) => formData.append("images", resizedImg)); | |
// I've refactored this. you can handle errors with try catch if you want. | |
let res = await axios.post("https://your-endpoint/upload", formData); | |
console.log(res.data); | |
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | |
}; | |
</script> | |
<h1>Fill this form!</h1> | |
<input type="file" bind:files={rawImgs} multiple /> | |
<br/> | |
<button on:click={onSubmit}>Submit</button> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment