Skip to content

Instantly share code, notes, and snippets.

@souljorje
Last active February 5, 2026 17:44
Show Gist options
  • Select an option

  • Save souljorje/d4ffe91532266cf365fd1d3f1526dee9 to your computer and use it in GitHub Desktop.

Select an option

Save souljorje/d4ffe91532266cf365fd1d3f1526dee9 to your computer and use it in GitHub Desktop.
Fetch image/file and convert to File
/*
* @example
* getImgName('http://localhost.dev/uploads/image.jpg') // 'image'
*/
const getFileName = (url) => url.slice(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
const fetchFile = async (url, fileName = getFileName(url)) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`);
}
const blob = await response.blob();
const mimeType = response.headers.get('content-type') || blob.type;
return new File([blob], fileName, { type: mimeType });
};
@olivsinz
Copy link

olivsinz commented Jun 1, 2023

Thanks for this.

Here's a fix that works for me:

const getImgName = (url) => url.slice(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));

Because my URL was
// Example src http://localenv.test/uploads/bbf9e6e15a3841fba491dfd3972da6a4.jpg

SO I had to edit the getImgName using lastIndexOf to get the file extension.

@souljorje
Copy link
Author

@olivsinz you're right! fixed

@olivsinz
Copy link

olivsinz commented Feb 5, 2026

@olivsinz you're right! fixed

Got it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment