Last active
March 7, 2024 05:56
-
-
Save eimg/8f49996bf5457b6899b987a05ef84736 to your computer and use it in GitHub Desktop.
JavaScript FormData Upload
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
const getFile = async () => { | |
const [fileHandle] = await window.showOpenFilePicker({ | |
types: [ | |
{ | |
description: "Images", | |
accept: { | |
"image/*": [".png", ".jpeg", ".jpg"], | |
}, | |
}, | |
], | |
excludeAcceptAllOption: true, | |
multiple: false, | |
}); | |
return await fileHandle.getFile(); | |
}; | |
const changePhoto = async e => { | |
const uid = "auto_id"; | |
const api = "api_url"; | |
const file = await getFile(); | |
// setPhoto(URL.createObjectURL(file)); | |
const fileName = | |
file.type === "image/png" ? `${uid}-cover.png` : `${uid}-cover.jpg`; | |
const formData = new FormData(); | |
formData.append("photo", file, fileName); | |
const res = await fetch(`${api}/users/photo`, { | |
method: "post", | |
body: formData, | |
}); | |
return res.ok; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment