Last active
June 1, 2023 11:08
-
-
Save souljorje/d4ffe91532266cf365fd1d3f1526dee9 to your computer and use it in GitHub Desktop.
Fetch image and convert to File (axios)
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
// 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 }); | |
} |
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.jpg
SO I had to edit the getImgName using lastIndexOf to get the file extension.