简体   繁体   中英

Make AsyncFileUpload accepts only images files Asp.Net Webforms

I am using asyncfileupload control, I want to accept only images. I used the accept attribute but it didn't work and used OnClientUploadComplete event to catch the content type and stop the uploading on server side, the event didn't fire and caused the OnUploadedComplete to not fire too! And I don't know how to stop it from uploading on the server side. I tried to check the contentType in OnUploadedComplete event, it fires and goes to 'else' but it doesn't show the message that it's supposed to show. Any suggestion?

C# code:

`protected void fileUpload_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        if (fuImage.HasFile)
        {
            string contentType = fuImage.ContentType;
            if (contentType == "image/jpeg" || contentType == "image/gif"
              || contentType == "image/png")
            {
                string fileName = Path.GetFileName(e.FileName);
                string fileUploadPath = Path.Combine(Server.MapPath("~/images/Resturant"), fileName);
                fuImage.SaveAs(fileUploadPath);

                var url = "~/images/Resturant/" + fileName;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "fileName",
                      "top.$get(\"" + hdfImagePath.ClientID + "\").value = '" + url + "';", true);
            }
            else
            {
            ucMessage1.MessageTitle = "Error Message";
            ucMessage1.MessageDetail = "Please Choose a valid image!";
            ucMessage1.MessageImage = "X";
            ucMessage1.Show();
        }
    }
}`

Design:

<ajaxToolkit:AsyncFileUpload ID="fuImage" runat="server" OnUploadedComplete="fileUpload_UploadedComplete" />

成功上传文件后,服​​务器端将触发UploadedComplete事件,这意味着它无法在上传之前检查文件扩展名。

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