2012-10-06 28 views
0

突然之前顯示的圖片停止顯示在頁面上並檢查文件夾*發現圖像在我點擊它們時未顯示。調試我的代碼我發現註釋行導致它。下面的代碼是否在操縱流?使用stream和fileupload以某種方式操縱結果

public ActionResult UploadPhoto(UserPhotoUploadModel photoFileModel) 
{ 
        HttpPostedFileBase photoFile = photoFileModel.PhotoFile; 
    string uploadPath = Server.MapPath("~/Content/users/photos"); 
    string autoFileName = String.Format("{0}_{1}", Guid.NewGuid().ToString(), filename); 
    string fileDestName = Path.Combine(uploadPath, autoFileName); 

    //Starting from here is where the issue lies 
    Stream imgStream = photoFile.InputStream; 
    using (imgStream) 
    { 
     Image img = Bitmap.FromStream(imgStream); 
     int width = img.Width; 
     int height = img.Height; 

     if (width > 100 || height > 100) 
     { 
      ModelState.AddModelError("PhotoFile", "Photo dimension should be 100 by 100 or less"); 
      return View(photoFileModel); 
     } 
    } 
    //the issue ends here 

    photoFile.SaveAs(fileDestName); 

    return RedirectToAction("Profile", new {id = loggedinUser.ProviderUserKey}); 
} 

保存的文件具有正確的圖像擴展,例如, JPG。正在使用流來確定上傳圖像的尺寸。

評論部分是導致此問題的原因。我怎樣才能做到這一點與輸入流仍然完好?

謝謝。

+0

沒有評論區域,圖像保存完好,但是當我添加它時,圖像保存但空白/或不作爲真實圖像,所以它不顯示在瀏覽器。我認爲'using'塊在調用'photoFile.SaveAs(fileDestName)'之前就已經清除了流。我知道這是因爲將'photoFile.SaveAs(fileDestName)'移動到'使用'作品 – codingbiz

+0

是什麼問題? –

+0

如何防止流被篡改,因爲顯然,垃圾/沒有任何內容正在保存到文件 - 文件存在於位置但不是有效的映像文件 – codingbiz

回答

0

問題是這樣的線:

return View(photoFileModel); 

當代碼擊中該線離開的方法的。因此,這條線不被執行:

photoFile.SaveAs(fileDestName); 
+0

不!該文件被保存爲空或無效圖像內容 – codingbiz

+0

當您聲明photoFile時會創建空文件或無效文件。註釋返回查看(photoFileModel);並測試它 –