Skip to content

Instantly share code, notes, and snippets.

@eimg
Last active March 7, 2024 05:56
Show Gist options
  • Save eimg/8f49996bf5457b6899b987a05ef84736 to your computer and use it in GitHub Desktop.
Save eimg/8f49996bf5457b6899b987a05ef84736 to your computer and use it in GitHub Desktop.
JavaScript FormData Upload
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