[英]image upload and image.ContentLenght > 0
我在對象街上有一些照片。 我正在嘗試以與創建新街道對象相同的形式實施上傳。 因此,圖像與字段的MVC Web表單
現在,在create.cshtml頁面上,我具有帶StreetName
和StreetNumber
字段的表單,並且
<input type="file" name="postedImages" />
<input type="file" name="postedImages" />
<input type="file" name="postedImages" />
提交此表單后,我會將這些數據發送到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
}
}
}
如您所見,如果我張貼了Web表單上提供的確切數量的圖像,則一切都很好,但是如果我發送1或2張圖像,則會發生錯誤。
如何解決呢? 謝謝
在訪問ContentLength
屬性之前添加null
檢查
if((image!=null) && (image.ContentLength >0))
{
//process and save images
}
foreach(var image in postedImages.Where(pi => pi != null))
您可以執行以下操作:
If(image != null)
if(image.ContentLength > 0)
{
//code
}
在獲取屬性之前,請檢查其null是否是錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.