2012-05-12 33 views
0

我在ASP.NET MVC3中開發,我有下面的代碼保存在Sql Server 2008中的文件,它適用於IE瀏覽器(我使用IE9),但在Firefox中,我得到錯誤「索引超出範圍,必須是非負數,小於集合的大小。\ r \ n參數名稱:索引」,我該如何解決這個問題?謝謝Valums Ajax文件上傳在IE瀏覽器但不在Firefox中工作

[HttpPost] 
    public ActionResult FileUpload(string qqfile) 
    { 
     try 
     { 
      HttpPostedFileBase postedFile = Request.Files[0]; 
      var stream = postedFile.InputStream; 
      App_MessageAttachment NewAttachment = new App_MessageAttachment 
      { 
       FileName = postedFile.FileName.ToString().Substring(postedFile.FileName.ToString().LastIndexOf('\\') + 1), 
       FilteContentType = postedFile.ContentType, 
       MessageId = 4, 
       FileData = new byte[postedFile.ContentLength] 
      }; 
      postedFile.InputStream.Read(NewAttachment.FileData, 0, postedFile.ContentLength); 
      db.App_MessageAttachments.InsertOnSubmit(NewAttachment); 
      db.SubmitChanges(); 
     } 
     catch (Exception ex) 
     { 
      return Json(new { success = false, message = ex.Message }, "application/json"); 
     } 
     return Json(new { success = true }, "text/html"); 
    } 

回答

2

Valums Ajax上傳有2種模式。如果它確認瀏覽器支持HTML5 File API(無疑是FireFox的情況),它將使用此API而不是使用enctype="multipart/form-data"請求。因此,在你的控制器動作,您需要考慮這些差異,在支持現代瀏覽器的HTML5的情況下直接讀取Request.InputStream

[HttpPost] 
public ActionResult FileUpload(string qqfile) 
{ 
    try 
    { 
     var stream = Request.InputStream; 
     var filename = Path.GetFileName(qqfile); 

     // TODO: not sure about the content type. Check 
     // with the documentation how is the content type 
     // for the file transmitted in the case of HTML5 File API 
     var contentType = Request.ContentType; 
     if (string.IsNullOrEmpty(qqfile)) 
     { 
      // IE 
      var postedFile = Request.Files[0]; 
      stream = postedFile.InputStream; 
      filename = Path.GetFileName(postedFile.FileName); 
      contentType = postedFile.ContentType; 
     } 
     var contentLength = stream.Length; 

     var newAttachment = new App_MessageAttachment 
     { 
      FileName = filename, 
      FilteContentType = contentType, 
      MessageId = 4, 
      FileData = new byte[contentLength] 
     }; 
     stream.Read(newAttachment.FileData, 0, contentLength); 
     db.App_MessageAttachments.InsertOnSubmit(newAttachment); 
     db.SubmitChanges(); 
    } 
    catch (Exception ex) 
    { 
     return Json(new { success = false, message = ex.Message }); 
    } 
    return Json(new { success = true }, "text/html"); 
} 

的代碼可能需要一些調整。我現在沒有時間對其進行測試,但您明白了:對於支持HTML5的瀏覽器,文件直接寫入請求的主體,而對於不支持File API的瀏覽器,文件數據將被傳輸使用標準multipart/form-data編碼。

相關問題