5

Uploading files works fine but now I'm trying to validate file extensions and looks like there's some interference between FileUpload1 and FileUpload2.

FileUpload1 is used for uploading .jpg or .png images, and FileUpload2 for uploading .pdf files.

Here's the code which is executed on BtnInsert_Click event:

protected void BtnInsert_Click(object sender, EventArgs e)
{
    string[] validPhotoFile = { ".jpg", ".png" };
    string validPDFFile = ".pdf";

    string photoExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
    string pdfExt = System.IO.Path.GetExtension(FileUpload2.PostedFile.FileName);

    bool isValidPhotoFile = false;
    bool isValidPDFFile = false;

    for (int i = 0; i < validPhotoFile.Length; i++)
    {
        if (photoExt == "." + validPhotoFile[i])
        {
            isValidPhotoFile = true;
            break;
        }
    }

    for (int i = 0; i < validPDFFile.Length; i++)
    {
        if (pdfExt == "." + validPDFFile[i])
        {
            isValidPDFFile = true;
            break;
        }
    }

    if (!isValidPhotoFile)
    {
        PhotoErrorMessage.Text = "Upload .jpg or .png image!";
    }

    if (!isValidPDFFile)
    {
        PDFErrorMessage.Text = "Upload .pdf file!";
    }

    else
    {
        string photoFilPath = Path.GetFileName(FileUpload1.PostedFile.FileName.ToString());
        string pdfFilPath = Path.GetFileName(FileUpload2.PostedFile.FileName.ToString());

        string photoPath = Server.MapPath(@"~/PDFCover/" + fotoFilPath);
        string pdfPath = Server.MapPath(@"~/PDF/" + pdfFilPath);

        FileUpload1.PostedFile.SaveAs(photoPath);
        FileUpload2.PostedFile.SaveAs(pdfPath);

        SqlCommand cmd = new SqlCommand("INSERT INTO Book(Title,Content...) VALUES ('" + TextBox1.Text
            + "','" + TextBox2.Text + ... + "','" + "~/PDFCover/" + photoFilPath
            + "','" + "~/PDF/" + pdfFilPath + "')", con);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

Now even if I choose to upload valid files it's showing label error messages to upload valid files.

user2969489
  • 179
  • 3
  • 8
  • 14
  • Yes both files at the same time. In this case the image and the pdf file. – user2969489 Sep 12 '14 at 11:31
  • 1
    Extensions are not the way to validate a file type. What if I use ".jpeg", or even no extension at all? The proper way, albeit more expensive at runtime, is parsing the file. In fact, I often find it necessary to parse image files uploaded to a server, to scale them down, for example in case the user uploaded a 41 megapixel file for a profile picture. – Kris Vandermotten Sep 12 '14 at 11:31
  • @Kris is is not really expensive as jpg, png and pdf have its own file header format, which lets you identify file in 8 to 20 bytes. – PTwr Sep 12 '14 at 11:33
  • @PTwr True. Then again, a "full parse" is a more thorough validation. And like I said, I often need to do a full parse anyway, especially for images, to scale them down. – Kris Vandermotten Sep 12 '14 at 11:36
  • @KrisVandermotten If user is too lazy to scale down image before uploading you can try [tricking their machine in doing this job](http://stackoverflow.com/questions/10333971/html5-pre-resize-images-before-uploading) ;) – PTwr Sep 12 '14 at 11:40
  • @PTwr Brilliant! I had never thought of this. Thanks for the tip. – Kris Vandermotten Sep 12 '14 at 11:43
  • possible duplicate of [Determine file type of an image](http://stackoverflow.com/questions/55869/determine-file-type-of-an-image) – MikeSmithDev Sep 12 '14 at 12:55

2 Answers2

11
bool CheckFileType(string fileName)
{
    string ext = Path.GetExtension(fileName);
    switch (ext.ToLower())
    {
        case ".gif":
            return true;
        case ".jpg":
            return true;
        case ".jpeg":
            return true;
        case ".png":
            return true;
        default:
            return false;
    }
}

if (CheckFileType(fuImage.FileName))
{
 //..........
}

or use RegularExpressionValidator:

<asp:RegularExpressionValidator 
     ID="regexValidateImageFil" runat="server" ControlToValidate="fuImage" 
     ErrorMessage="file type not allow." 
     ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.jpg|.JPG|.jpeg|.JPEG|.bmp|.BMP|.gif|.GIF|.png|.PNG)$"></asp:RegularExpressionValidator>
Chưa biết
  • 919
  • 8
  • 6
0

are you uploading both files at the same time, or only one at a time? if it is only one at a time, then one of those values is always going to be false.

You are also adding a period in front of your validPhotoFile and validPDFFile, change your code like this.

for (int i = 0; i < validPhotoFile.Length; i++)
{
    if (photoExt == validPhotoFile[i]) // remove the period here it is already in your variables above
    {
        isValidPhotoFile = true;
        break;
    }
}

for (int i = 0; i < validPDFFile.Length; i++)
{
    if (pdfExt == validPDFFile[i]) // remove the period here it is already in your variables above
    {
        isValidPDFFile = true;
        break;
    }
}
mmeasor
  • 459
  • 3
  • 19