2013-01-20 33 views
3

我試圖預覽用戶試圖上傳的圖像。 這是我使用的代碼。這在所有主流瀏覽器都可以正常工作,但我想知道是否有更好的方法來實現這一點而不使用會話(即使我正在清除會話)? 我不想使用Flash。使用Fileupload預覽圖像asp.net mvc和jquery

@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { id = "fileuploadform", @enctype = "multipart/form-data" })) 
    { 
     <input id="fileupload" type="file" onchange="ChangeImage()" name="files" multiple> 
     <div id="preview"> 
      <img src="#" id="imgThumbnail" alt="preview" /> 
     </div> 

    } 
      <script> 
      $(function ChangeImage() { 
       $('#fileuploadform').fileupload({ 
        done: function (e, data) { 
         var d = new Date(); 
         $('#imgThumbnail')[0].src = "/Home/ImageLoad?a=" + d.getTime(); 
        } 
       }); 
      }); 
     </script> 

[HttpPost] 
public ActionResult UploadImage(IEnumerable<HttpPostedFileBase> files, PostViewModel model) 
{ 

    Session["ContentLength"] = Request.Files[0].ContentLength; 
    Session["ContentType"] = Request.Files[0].ContentType; 
    byte[] b = new byte[Request.Files[0].ContentLength]; 
    Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength); 
    Session["ContentStream"] = b; 
    return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength); 
} 

    public ActionResult ImageLoad(int? id) 
    { 
     byte[] b = (byte[])Session["ContentStream"]; 
     int length = (int)Session["ContentLength"]; 
     string type = (string)Session["ContentType"]; 
     Session["ContentLength"] = null; 
     Session["ContentType"] = null; 
     Session["ContentStream"] = null; 
     return File(b, type); 
    } 

回答

3

您是否試過這種解決方案?

Preview an image before it is uploaded

該解決方案是純粹的客戶端,並沒有需要被上傳到前預覽您的服務器。 :)

+0

我之前看到了這一點,但在IE 8不工作。 – user636525

0

你可以提高你的動作的代碼是這樣的:

HttpPostedFileBase picFile = Request.Files["fileUpload"]; 
if (picFile != null && picFile.ContentLength > 0) 
{ 
    byte[] pic = new byte[picFile.ContentLength]; 
    picFile.InputStream.Read(pic, 0, picFile.ContentLength); 
    // you can use pic .... 
}