简体   繁体   中英

Upload file image validation

I have these codes as my validation before someone can upload an image. however when i try to upload different files like video files and etc. it is still pushing through? what am i missing here? here is my whole code behind. im not sure what you are looking for im sorry. its just its accepting everything that i try to upload and it uploads it but no image.

protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["IslandGasAdminPM"] != null)
        {
            if (!IsPostBack)
            {
                GetCategories();

                AddSubmitEvent();
            }
            if (Request.QueryString["alert"] == "success")
            {
                Response.Write("<script>alert('Record saved successfully')</script>");
            }
        }
        else
        {
            Response.Redirect("LogIn.aspx");
        }
    }
    private void AddSubmitEvent()
    {
        UpdatePanel updatePanel = Page.Master.FindControl("AdminUpdatePanel") as UpdatePanel;
        UpdatePanelControlTrigger trigger = new PostBackTrigger();
        trigger.ControlID = btnSubmit.UniqueID;

        updatePanel.Triggers.Add(trigger);
    }
    private void GetCategories()
    {
        ShoppingCart k = new ShoppingCart();
        DataTable dt = k.GetCategories();
        if (dt.Rows.Count > 0)
        {
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataSource = dt;
            ddlCategory.DataBind();
        }
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (uploadProductPhoto.PostedFile != null)
        {
            SaveProductPhoto();

            ShoppingCart k = new ShoppingCart()
            {
                ProductName = txtProductName.Text,
                ProductImage = "~/ProductImages/" + uploadProductPhoto.FileName,
                ProductPrice = txtProductPrice.Text,
                ProductDescription = txtProductDescription.Text,
                CategoryID = Convert.ToInt32(ddlCategory.SelectedValue),
                TotalProducts = Convert.ToInt32(txtProductQuantity.Text)
            };
            k.AddNewProduct();
            ClearText();
            Response.Redirect("/Admin/AddNewProduct.aspx?alert=success");
        }
        else
        {
            Response.Write("<script>alert('Please upload photo');</script>");
        }
    }
    private void ClearText()
    {
        uploadProductPhoto = null;
        txtProductName.Text = String.Empty;
        txtProductPrice.Text = String.Empty;
        txtProductDescription.Text = String.Empty;
        txtProductQuantity.Text = String.Empty;
    }
    private void SaveProductPhoto()
    {
        if (uploadProductPhoto.PostedFile != null)
        {
            string filename = uploadProductPhoto.PostedFile.FileName.ToString();
            string fileExt = System.IO.Path.GetExtension(uploadProductPhoto.FileName);

            //check filename length
            if (filename.Length > 96)
            {
                Response.Write("Image should not exceed 96 characters");
            }
            //check file type
            else if (fileExt != ".jpg" && fileExt != ".jpeg" && fileExt != ".png" && fileExt != ".bmp")
            {
                Response.Write("Only jpg,jpeg,bmp and png are allowed");
            }
            //check file size
            else if (uploadProductPhoto.PostedFile.ContentLength > 4000000)
            {
                Response.Write("Image should not exceed 4MB");
            }
            //Save images to folder
            else
            {
                uploadProductPhoto.SaveAs(Server.MapPath("~/ProductImages/" + filename));
            }
        }

You seem to be creating a variable 'filename' and then not using it in the next line when you attempt to get the extension. I'm not aware of the detail of what you're doing, but that's an immediate red flag for me and might be involved.

If you can provide some examples of the value of the 'filename' and 'uploadProductPhoto.FileName' then I'll be able to help you work out what's going on.

Use regular expression validation control ,The expression for video formats is:

ValidationExpression=/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.avi|.AVI|.WMV|.wmv|.wav|.WAV|.mpg|.MPG|.mid|.MID|.asf|.ASF|.mpeg|.MPEG)$/

The regular expression to validate audio file formats is:

ValidationExpression=/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.mp3|.MP3|.mpeg|.MPEG|.m3u|.M3U)$/

Edit: The regular expression to validate image file formats is:

ValidationExpression=/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpeg|.JPEG|.gif|.GIF|.png|.PNG|.JPG|.jpg|.bitmap|.BITMAP)$/

and:

<asp:FileUpload ID="fileUploadVideo" runat="server" />           
<asp:RegularExpressionValidator ID="RegularExpressionValidator7"

 runat="server" ControlToValidate="fileUploadVideo"

ErrorMessage="Only .avi, .mpg, .wav, .mid, .wmv, .asf and .mpeg Video formats are allowed." ForeColor="Red"

ValidationExpression="/^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.avi|.AVI|.WMV|.wmv|.wav|.WAV|.mpg|.MPG|.mid|.MID|.asf|.ASF|.mpeg|.MPEG)$/"

ValidationGroup="PartnerProfileUpdate" SetFocusOnError="true"></asp:RegularExpressionValidator>

See this link for complete article.

Because your SaveProductPhoto does not throw exception when checked failure,there is two way to avoid your problem:

  1. throw exception
  2. add Response.End() below your Response.Write code

also, validate the file ext is not a good idea,you can validate the InputStream,read the first two byte,and check them

//byte[] bytes = new byte[2];  
//string.Format("{0}{1}",bytes[0],bytes[1])  
//255216 is jpg;7173 is gif;6677 is BMP,13780 is PNG;7790 is exe,8297 is rar 

worked it out using regex. here is the expression.

ValidationExpression="^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF|PNG|png)$"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM