简体   繁体   中英

Image is NULL when I try to upload image ASP.NET

  • Set up a form where a user can fill a form in which they have to upload an image.

Code:

string FileName = Path.GetFileNameWithoutExtension(customerImage.ImageFile.FileName);

string FileExtension = Path.GetExtension(customerImage.ImageFile.FileName);

FileName = DateTime.Now.ToString("yyyyMMdd") + "-" + FileName.Trim() + FileExtension;

string UploadPath = ConfigurationManager.AppSettings["UserImagePath"].ToString();

customerImage.Image = UploadPath + FileName;

customerImage.ImageFile.SaveAs(customerImage.Image);

Problematic line:

string FileName = Path.GetFileNameWithoutExtension(customerImage.ImageFile.FileName);

Error: UPLOAD IMAGE ERROR

PLEASE HELP IM A COLLEGE STUDENT AND THIS IS FOR A FINAL PROJECT:((((((((((

You have a object reference error (Null Reference Exception),most probably the file upload control has not been initialized properly or there is not file attached to the control when sending the request to server side.

If customerImage is a ASP File Upload control you can access the file name like below:

FileUpload1.FileName

Pleas see below sample: For the HTML

<asp:FileUpload ID="FileUpload1" runat="server" />  
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click"/>  
<br />  
<asp:Image ID="Image1" runat="server" />  

For Server Side

protected void Button1_Click(object sender, EventArgs e) {  
             StartUpLoad();  
}  
     
private void StartUpLoad() {  
        //get the file name of the posted image  
        string imgName = FileUpload1.FileName;  
        //sets the image path  
        string imgPath = "ImageStorage/" + imgName;            
       //get the size in bytes that  
  
       int imgSize = FileUpload1.PostedFile.ContentLength;  
      
       //validates the posted file before saving  
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {  
           // 10240 KB means 10MB, You can change the value based on your requirement  
                if (FileUpload1.PostedFile.ContentLength > 10240) {  
                           Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);  
                 }  else {  
                           //then save it to the Folder  
                           FileUpload1.SaveAs(Server.MapPath(imgPath));  
                           Image1.ImageUrl = "~/" + imgPath;  
                           Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Image saved!')", true);  
                }  
    
          }  
}  

Try this and see what is wrong with your code.

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