上传文件图片验证

时间:2015-07-08 11:07:42

标签: c# asp.net 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));
            }
        }

4 个答案:

答案 0 :(得分:0)

您似乎正在创建变量'filename',然后在尝试获取扩展时不在下一行中使用它。我不知道你正在做什么的细节,但这对我来说是一个直接的红旗,可能会参与其中。

如果您可以提供'filename'和'uploadProductPhoto.FileName'值的一些示例,那么我将能够帮助您了解正在发生的事情。

答案 1 :(得分:0)

使用正则表达式验证控件,视频格式的表达式为:

Intent action = new Intent(Intent.ACTION_GET_CONTENT);          
            action.putExtra(Intent.EXTRA_LOCAL_ONLY, true);         
action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(action, "Upload file from..."),Constants.FILE_CHOOSER_REQUEST_CODE );

验证音频文件格式的正则表达式是:

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

编辑:验证图像文件格式的正则表达式为:

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

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

有关完整文章,请参阅this链接。

答案 2 :(得分:0)

因为SaveProductPhoto在检查失败时没有抛出异常,有两种方法可以避免您的问题:

  1. 抛出异常
  2. Response.End()代码
  3. 下方添加Response.Write

    另外,验证文件ext不是一个好主意,你可以验证InputStream,读取前两个字节,并检查它们

    //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 
    

答案 3 :(得分:0)

使用正则表达式进行解决。这是表达方式。

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