2017-10-07 76 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); 
    }