Hi!
I have a byte array filled from a file uploaded. But, in another part of the code, I need to know this file type uploaded from the byte[] so I can render the correct content-type to browser!
Thanks!!
Hi!
I have a byte array filled from a file uploaded. But, in another part of the code, I need to know this file type uploaded from the byte[] so I can render the correct content-type to browser!
Thanks!!
You can't know it from the byte stream, but you can store the MIME type when you initially populate the byte[]
.
Short answer: you can't
Longer answer: Usually, programs use the file extension to know what type of file they're dealing with. If you don't have that extension, you can only make guesses... for instance, you could look at the first few bytes and check if you recognize a well-known header (XML declaration tag for instance, or bitmap or JPEG header). But that will always be a guess in the end : without some metadata of information about the content, an array of bytes is just meaningless...
You don't want to do it that way. Call Path.GetExtension when the file is uploaded, and pass the extension around with the byte[].
Not sure, but maybe you should investigate about magic numbers.
Update: Reading about it, I don't think it's very reliable though.
Reminds me of back in the day we, er um "some people" used to share 50MB rar files on the early free image hosting sites, by just adding the .gif extension to the .rar filename.
Clearly if you are public facing and your are expecting a certain file type, and you have to be sure it is that file type, then you can't just trust the extension.
On the other hand, if your app would have no reason to distrust the the uploaded extension and or MIME type, then just get those when the file is uploaded like the answers you received from @rossfabircant and @RandolphPotter. create a type that has the byte[], as well as the original extension or mimetype, and pass that around.
If you need to verify that the file is actually a certain expected type like a valid .jpeg, or .png you can try to interpret the file as those types and see if it opens successfully. (System.Drawing.Imaging.ImageFormat)
If you are trying to classify the file only from the binary contents, and it could be any format in the whole wide world, that is really a tough, open-ended problem and there is no 100% reliable way to do it. You could invoke TrID against it, and there are likely similar forensics tools used by law enforcement investigators if you can find (and afford) them.
If you don't have to do it the hard way, don't.