Let' say a file (e.g. myfile.jpeg) encoded in Base64 String and given to me. There is no way I know what the file type was. I'd like to decode the string into a file (an image in this example). How do I know the type of the file (e.g jpeg)?
Asked
Active
Viewed 2.7k times
9
-
Possible duplicate of [How to identify file type by base 64 encoded string of a image](https://stackoverflow.com/questions/25763533/how-to-identify-file-type-by-base-64-encoded-string-of-a-image) – naXa stands with Ukraine Jun 22 '17 at 12:09
2 Answers
7
In general, a base 64-encoded string could contain absolutely any data, so there is no way to know its file type.
To determine if it is an instance of a JPEG image, you'd need to base64-decode it, and then do something like checking its magic number, which is useful in telling you what the file isn't. You'd still need to do more work to determine if it is a valid JPEG image.

Andy Turner
- 137,514
- 11
- 162
- 243
1
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=
Is a sample image. Just split it with the first slash and get array index 1. Supposing the image is coming from a trusted client.

F.O.O
- 4,730
- 4
- 24
- 34
-
2It's not a base64 string. The real base64 starts on "iVBORw0K". Forget the before content. You don't have this on real conversion. This is exactly what we are desiring to get. – rios0rios0 Nov 09 '20 at 12:40