开发者

Getting the type of file from the ASP.NET FileUpload control?

I want to get the type of file uploaded using the开发者_开发知识库 ASP.NET FileUpload control. When I upload a file, I want to be able to get the type of file uploaded, so I can assign a an icon to the file (such as a word, excel, pdf icon).

Here is the problem, I can't go off the file extension because a file could be called test.xxxxxxxx and be a valid pdf file, or a file might not have an extension.

The other option is to read the content-type, but with some of these appear not to be standard or in a simple to read format such as excel files, so is there another option to determine the file type?


I would review the process that names a PDF file "test.xxxxxxxx" without a ".pdf" extension. Most workflows that files have some kind of naming convention (manual or automated)

If you cannot read the extension, the file format will need to be detected by interogating markers that make it a known file format: eg: if the stream starts with or contains "%PDF" its a PDF.


If you don't know the extension, then you would have to know the file format of popular file types and then read the file and see if it matches one of your known formats. That doesn't sound optimal, though.


An easy way to check the true type of a file server side, using System.IO.BinaryReader, is described here:

http://forums.asp.net/post/2680667.aspx

and VB version here:

http://forums.asp.net/post/2681036.aspx

You'll need to know the binary 'codes' for the file type(s) you're checking for, but you can get those by implementing this solution and debugging the code.

Also note that when the BinaryReader is closed with the r.Close() statement, this will make FileUploader.HasFile = False

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜