C# 图像上传和image.contentLength>;0

C# 图像上传和image.contentLength>;0,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我有一些照片。我试图在创建新街道对象的同一表单上实现上传。因此,想象一个带有字段的mvc web表单 街道名称 街道号码 照片1 照片2 照片3 现在,在create.cshtml页面上,我有了带有StreetName和StreetNumber字段和 <input type="file" name="postedImages" /> <input type="file" name="postedImages" /> <input type="file" name

我有一些照片。我试图在创建新街道对象的同一表单上实现上传。因此,想象一个带有字段的mvc web表单

  • 街道名称
  • 街道号码
  • 照片1
  • 照片2
  • 照片3
现在,在create.cshtml页面上,我有了带有
StreetName
StreetNumber
字段和

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

在提交此表格时,我将这些数据发送给街道控制员进行进一步处理

 [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
       }
    }

 }
[HttpPost]
公共操作结果创建(StreetViewModelNewData、IEnumerable PosteImage)
{
//创建对象并保存StrateName和streetnumber
//处理发布的图像
foreach(PosteImage中的var图像)
{
//如果我只发布视图中的一个或两个图像,则会出现此错误
如果(image.ContentLength>0)
{
//处理和保存图像
}
}
}
正如您可以在我的评论行中看到的,如果我在web表单上发布确切数量的图像,一切都很好,但如果我发送1或2个图像,则会发生错误


如何解决这个问题?谢谢

在访问
ContentLength
项目之前添加
null
检查

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

在访问
ContentLength
项目之前添加
null
检查

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

foreach(postedImage中的var image.Where(pi=>pi!=null))
foreach(postedImage中的var image.Where(pi=>pi!=null))
您可以这样做:

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

在获取属性之前,请检查其是否为null,这是错误的原因。

您可以执行以下操作:

If(image != null)
    if(image.ContentLength > 0)
        {
           //code
        }
在获取属性之前检查其是否为null,这是错误的原因