2017-10-07 85 views
0

有人可以幫助我通過將它們轉換成字節數組來上傳大文檔(多個)嗎?C#MVC - 上傳多個大文件創建字節數組

我的代碼目前在沒有字節數組的情況下工作,但當然如果文檔很大,它就會失敗。

控制器:

[HttpPost] [ValidateAntiForgeryToken] 公共的ActionResult創建(發票的發票) { 如果(ModelState.IsValid) { 列表fileDetails =新列表(); (int i = 0; < Request.Files.Count; i ++) { var file = Request.Files [i];

  if (file != null && file.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       FileDetail fileDetail = new FileDetail() 
       { 
        FileName = fileName, 
        Extension = Path.GetExtension(fileName), 
        Id = Guid.NewGuid() 
       }; 
       fileDetails.Add(fileDetail); 

       var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), 
       fileDetail.Id + fileDetail.Extension); 
       file.SaveAs(path); 

      } 
     } 

     invoice.FileDetails = fileDetails; 
     db.Invoices.Add(invoice); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 
    return View(invoice); 
} 

和形式元素:

任何幫助將非常感激。

回答

0

Sorted!

[HttpPost] [ValidateAntiForgeryToken] 公共的ActionResult創建(發票的發票) { 如果(ModelState.IsValid) { 列表fileDetails =新列表();

  for (int i = 0; i < Request.Files.Count; i++) 
      { 
       HttpPostedFileBase httpPostedFileBase = Request.Files[i]; 

       if (httpPostedFileBase != null) 
       { 
        Stream stream = httpPostedFileBase.InputStream; 
        BinaryReader bReader = new BinaryReader(stream); 
        byte[] bytes = bReader.ReadBytes((Int32)stream.Length); 
       } 

       HttpPostedFileBase postedFileBase = Request.Files[i]; 

       if (postedFileBase != null) 
       { 
        var fileName = Path.GetFileName(postedFileBase.FileName); 

        FileDetail fileDetail = new FileDetail() 
        { 
         FileName = fileName, 
         Extension = Path.GetExtension(fileName), 
         Id = Guid.NewGuid() 
        }; 
        fileDetails.Add(fileDetail); 
        //Save the Byte Array as File. 
        var path = Path.Combine(Server.MapPath("~/App_Data/Upload/"), 
         fileDetail.Id + fileDetail.Extension); 
        postedFileBase.SaveAs(path); 
        postedFileBase.InputStream.Flush(); 
       } 
      } 

      invoice.FileDetails = fileDetails; 
      db.Invoices.Add(invoice); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     return View(invoice); 
    }