简体   繁体   中英

ASP.NET Calling methods on user controls

I have created an user control as follows to upload images. In it's code behind I have the method to save the image.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCImageUploader.ascx.cs"
    Inherits="WebApplicationFor_ABC.UCImageUploader" %>
<div>
    <asp:FileUpload ID="FileUploadImage" runat="server" />
    <asp:Image ID="ImageThumbnail" runat="server" />
    <asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
<asp:CheckBox ID="CheckBoxDelete" runat="server" Text="Delete"/>

</div>

code behind as follows

 public partial class UCImageUploader : System.Web.UI.UserControl
    {
        public bool SaveImg()
        {
                        //file field isn't empty
        if (FileUploadImage.PostedFile != null)
        {

            //check file size
            HttpPostedFile img = FileUploadImage.PostedFile;

            if (img.ContentLength == 0) // no file uploaded
            {
                msg = "No file was uploaded";
                LblMsg.Text = msg;
                return false;
            }
            else if (img.ContentLength > fileSizeInKB * 1024) // file size exceeds limit
            {
                msg = "File size exceeds the limit. Max is " + fileSizeInKB + "KB";
                LblMsg.Text = msg;
                return false;
            }
            else // accepted file size
            {
                //check file extension jpg,jpeg,BMP

                string[] fileExtensions = { "jpg", "jpeg", "bmp" };

                if (!fileExtensions.Contains(Path.GetExtension(img.FileName).ToLower()))
                {
                    msg = "File extension must be of jpg,jpeg,bmp";
                    LblMsg.Text = msg;
                    return false;
                }

            }
        }
        msg = "Valid File";
        LblMsg.Text = msg;
        return valid;
    }

On another button's click event I want to call this SaveImg() method and save the Image. The problem is because of the postback image returns as null. How can i fix this.

为了访问图像,请勿通过文件上载控件来执行此操作,例如

FileUploadImage.SaveAs(savePath);

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