Last active
February 5, 2026 17:44
-
-
Save souljorje/d4ffe91532266cf365fd1d3f1526dee9 to your computer and use it in GitHub Desktop.
Fetch image/file and convert to File
This file contains hidden or 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
| /* | |
| * @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 }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.jpgSO I had to edit the getImgName using lastIndexOf to get the file extension.