how can we check file types before uploading them in asp.net?

13,628

Solution 1

Example:

// generate new Guid
Guid fileguid = Guid.NewGuid();

// set limit for images, 1920x1200 pixels
int imageWidth = 1920;
int imageHeight = 1200;
int maxFileSize = 8388608;
// web.config - httpRuntime - maxRequestLength="8192"
// 8,388,608 Bytes 
// 8,192 KB ( / 1024 ) 
// 8.00 MB ( / 1024 / 1024 )

string sConn = ConfigurationManager.ConnectionStrings["AssetsDBCS"].ConnectionString;
SqlConnection objConn = new SqlConnection(sConn);
objConn.Open();
SqlCommand objCmd = new SqlCommand("sp_FileStorage_New", objConn);
objCmd.CommandType = CommandType.StoredProcedure;

SqlParameter paramFileGuid = objCmd.Parameters.Add("@FileGuid", SqlDbType.UniqueIdentifier);
SqlParameter paramFileSubject = objCmd.Parameters.Add("@Subject", SqlDbType.VarChar);
SqlParameter paramFileContentType = objCmd.Parameters.Add("@ContentType", SqlDbType.VarChar);
SqlParameter paramFileData = objCmd.Parameters.Add("@BinaryData", SqlDbType.VarBinary);
SqlParameter paramFileSize = objCmd.Parameters.Add("@Filesize", SqlDbType.BigInt);
SqlParameter paramFileDesc = objCmd.Parameters.Add("@Description", SqlDbType.VarChar);
SqlParameter paramIsSLAFile = objCmd.Parameters.Add("@IsSLAFile", SqlDbType.Bit);
SqlParameter paramUserStamp = objCmd.Parameters.Add("@UserStamp", SqlDbType.VarChar);

paramFileGuid.Direction = ParameterDirection.Input;
paramFileSubject.Direction = ParameterDirection.Input;
paramFileContentType.Direction = ParameterDirection.Input;
paramFileData.Direction = ParameterDirection.Input;
paramFileSize.Direction = ParameterDirection.Input;
paramFileDesc.Direction = ParameterDirection.Input;
paramIsSLAFile.Direction = ParameterDirection.Input;
paramUserStamp.Direction = ParameterDirection.Input;

// read data
byte[] bData = new byte[fuOne.PostedFile.ContentLength];
Stream objStream = fuOne.PostedFile.InputStream;
objStream.Read(bData, 0, fuOne.PostedFile.ContentLength);

paramFileSubject.Value = txtSubject.Text;

objCmd.Parameters.Add("@FileName", SqlDbType.VarChar).Value = Path.GetFileName(fuOne.PostedFile.FileName);
objCmd.Parameters.Add("@Extension", SqlDbType.VarChar).Value = Path.GetExtension(fuOne.PostedFile.FileName);

paramFileGuid.Value = fileguid;

paramFileContentType.Value = fuOne.PostedFile.ContentType;
paramFileData.Value = bData;
paramFileSize.Value = fuOne.PostedFile.ContentLength;
paramFileDesc.Value = fuOne.PostedFile.FileName;
paramIsSLAFile.Value = cbIsSLAFile.Checked;
paramUserStamp.Value = ac.getUser();

if (fuOne.PostedFile.ContentLength < maxFileSize)
{

    switch (fuOne.PostedFile.ContentType)
    {
        case "image/pjpeg":
            {

                System.Drawing.Image iImage = System.Drawing.Image.FromStream(new MemoryStream(bData));

                if (iImage.Width > imageWidth || iImage.Height > imageHeight)
                {
                    lblStatus.Text = "The image width or height cannot be greater than " + imageHeight + " x " + imageWidth + " pixels";
                }
                else
                {
                    objCmd.ExecuteNonQuery();
                    objConn.Close();

                    hlDownload.Visible = true;
                    hlDownload.NavigateUrl = "Download.aspx?DownloadFileGuid=" + fileguid.ToString();
                    hlDownload.Text = "Click here to download the uploaded file";

                    hlShowFile.Visible = true;
                    hlShowFile.NavigateUrl = "Download.aspx?ShowFileGuid=" + fileguid.ToString();
                    hlShowFile.Text = "Click here to view the uploaded file";

                    lblStatus.Text = showUploadFileInfo(Path.GetFileName(fuOne.PostedFile.FileName), fuOne.PostedFile.ContentType, fuOne.PostedFile.ContentLength, iImage.Width, iImage.Height);
                }
                break;
            }
    }
}

Solution 2

before uploading, the only thing you have to go off of is the name. So you couldn't. You could upload it, inspect the contents of the file, and if it's not what you want, delete it.

Solution 3

You should never depend on the file extension to determine what the content of the file is. Remember that the extension could be renamed to anything at all.

The only way you can determine the file type is by looking at the file itself. You can't easily do that on the client. You would have to allow the file to be uploaded to a quarantine directory, then examine it in that directory on the server before moving the file to its ultimate, trusted location.

You should probably be virus-scanning the files in any case.

Solution 4

Telerik allows you to do client-side validation using the 'AllowedFileExtensions' property:

<telerik:RadUpload ID="RadUpload1" 
                runat="server" 
                InitialFileInputsCount="1"
                AllowedFileExtensions=".zip,.jpg,.jpeg"
             />

However other than server side you can't check for the content type of a file.

Michael

Share:
13,628
SilverLight
Author by

SilverLight

WEB DEVELOPER &amp; C# PROGRAMMER ASP.NET C# JQUERY JAVASCRIPT MICROSOFT AJAX MICROSOFT SQL SERVER VISUAL STUDIO

Updated on August 30, 2022

Comments

  • SilverLight
    SilverLight over 1 year

    how can we check file types (formats such as jpg) without using file extensions before uploading them with asp.net & c# ?

    i am using vs 2008 + asp.net + c# + TELERIK Controls (RadUpload)


    imagine that some body change the text file extension to jpg and select it in a upload conrol such as radupload ...

    how can we recognize that this file is truely jpg or not?

    • Nathan
      Nathan almost 13 years
      Why does this question have >1k views!!? lol
  • SilverLight
    SilverLight about 14 years
    (really really thanks a lot) (your code was about fileupload and i test contentType on RadUpload...) (but by doing that when u change a Text file extension to jpg so RadUpload Thinks the contenttype of that file is "image/pjpeg")(i test that) (so i think this problem exists in fileupload...) (can u explain that for us!)