0
votes

Could someone help me upload large documents (multiple) by converting those to byte array?

My code is currently working without the byte array but it fails of course if the documents are large.

Controller:

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Invoice invoice) { if (ModelState.IsValid) { List fileDetails = new List(); for (int i = 0; i < 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);
}

and the form element:

Any help will be much appreciated.

1

1 Answers

0
votes

Sorted!

[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Invoice invoice) { if (ModelState.IsValid) { List fileDetails = new List();

            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);
    }