Skip to content

Instantly share code, notes, and snippets.

@souljorje
Last active June 1, 2023 11:08
Show Gist options
  • Save souljorje/d4ffe91532266cf365fd1d3f1526dee9 to your computer and use it in GitHub Desktop.
Save souljorje/d4ffe91532266cf365fd1d3f1526dee9 to your computer and use it in GitHub Desktop.
Fetch image and convert to File (axios)
// https://stackoverflow.com/questions/48470407/client-side-convert-png-file-stream-into-file-object
// Example src http://localhost:1337/uploads/bbf9e6e15a3841fba491dfd3972da6a4.jpg
// @returns bbf9e6e15a3841fba491dfd3972da6a4
const getImgName = (url) => url.slice(url.lastIndexOf('/') + 1, url.indexOf('.'));
const srcToFile = async (src, fileName = getImgName(src)){
const response = await axios.get(src, {
responseType: 'blob'
});
const mimeType = response.headers['content-type'];
return new File([response.data], 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.

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