简体   繁体   中英

image upload and image.ContentLenght > 0

I have object street which have some photos. I'm trying to implement upload on the same form as where creating new street object. So image a mvc web form with fields

  • StreetName
  • StreetNumber
  • Photo1
  • Photo2
  • Photo3

Now, on the create.cshtml page I have form with StreetName and StreetNumber fields and

<input type="file" name="postedImages" />
<input type="file" name="postedImages" />
<input type="file" name="postedImages" />

On submiting this form I'm sending these data to the StreetController for further process

 [HttpPost]
 public ActionResult Create(StreetViewModel newData, IEnumerable<HttpPostedFileBase> postedImages)
 {
    //create object and save stretname and streetnumber
    //process posted images
    foreach(var image in postedImages)
    {
        //this is where error occured if I post only one or two images from my view
       if(image.ContentLength >0)
       {
          //process and save images
       }
    }

 }

As you can read inside my commented lines if I post exact number of images that are provided on the web form everything is fine, but If I send 1 or 2 images error occured.

How to solve this? Thanks

Add a null check before accessing the ContentLength proeprty

if((image!=null) && (image.ContentLength >0))
{
      //process and save images
}

foreach(var image in postedImages.Where(pi => pi != null))

You could do something like this:

If(image != null)
    if(image.ContentLength > 0)
        {
           //code
        }

Check if its null before you are getting a property, this is the reason for the error.

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