[英]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 因此,图像与字段的MVC Web表单
Now, on the create.cshtml page I have form with StreetName
and StreetNumber
fields and 现在,在create.cshtml页面上,我具有带StreetName
和StreetNumber
字段的表单,并且
<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 提交此表单后,我会将这些数据发送到StreetController进行进一步处理
[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. 如您所见,如果我张贴了Web表单上提供的确切数量的图像,则一切都很好,但是如果我发送1或2张图像,则会发生错误。
How to solve this? 如何解决呢? Thanks 谢谢
Add a null
check before accessing the ContentLength
proeprty 在访问ContentLength
属性之前添加null
检查
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. 在获取属性之前,请检查其null是否是错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.