I have an asp.net application where the users can upload files to our database.
Sometimes when they upload the files, the content-type
is set as "application/octet-stream"
which is a binary file.
When I ask the user, they say that they uploaded they say it was a .tif
file. Somehow the upload control sets it as "application/octet-stream"
.
When I upload the same .tif
file from my computer it uploads with the correct content type (application/octet-stream
).
I am using the following code to get the file extension
fileExtension = filUpload.PostedFile.FileName.Substring(filUpload.PostedFile.FileName.LastIndexOf(".") + 1)
sometimes it returns the file extension as "c:\documen"
or "j:\testing"
etc. I know that windows doesn't allow special characters in the filename.
You simply can't rely on the browser to submit a usable MIME media type. The client machine may not have any media type information set up for a particular filetype (which is likely the case for TIFF here), or it may not support sending media types at all, or there may be bugs in it (as there have been in the past with IE).
You also can't rely on the browser to submit a usable filename extension. The client machine may not use file extensions to determine the type of the file. (Indeed, Macs and modern Linux use multiple mechanisms to determine type, so any filename extension may be misleading, if one is present at all.)
For that matter, you can't even rely on the browser to submit a usable filename in the first place! Not every OS uses backslash character and dot for directory and extension separators; the submitted filename is effectively an opaque string which you can use for guessing some of the common cases, but you can't consider to be definitive.
So the only reasonable ways to determine the type of an uploaded file are:
Ask the user explicitly what type they're uploading.
Try to guess what type it might be from media type and trailing filename, falling back to asking the user what type it is.
If the types you want to allow are all ones with sniffable headers (as TIFF and most other image formats are), you can work out the type by looking at the contents of the file.
Use functions in the System.IO namespace to parse it out instead.
To get the extension, you would do this:
fileExtension = System.IO.Path.GetExtension(filUpload.PostedFile.FileName);
I believe that the user's browser sends a declared MIME type along with the file. It's then up to the browser to declare the type of the file. Different browsers may have different ability to infer the best MIME type from a file. When you get the file on your server, you might just check for the .tif[f] extension -- that's probably all the checking that the uploading browser will do anyways.