19

I want to give a facility on my form for user to upload files and save in Database. How is this done in ASP.NET MVC.

What DataType to write in my Model Class. I tried with Byte[], but during the scaffolding the solution could not generate the appropriate HTML for it in the corresponding View.

How are these cases handled?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mangesh Kaslikar
  • 591
  • 3
  • 13
  • 23

1 Answers1

44

You could use a byte[] on your model and a HttpPostedFileBase on your view model. For example:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

and then:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        byte[] uploadedFile = new byte[model.File.InputStream.Length];
        model.File.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

        // now you could pass the byte array to your model and store wherever 
        // you intended to store it

        return Content("Thanks for uploading the file");
    }
}

and finally in your view:

@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
        @Html.ValidationMessageFor(x => x.File)
    </div>

    <button type="submit">Upload</button>
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Hi, this is awesome, but as an absolute noob, where would be the best place to store the files, if for example, I am only wanting to allow the site administrator to upload files (application .exe file) that users can down load? – MoonKnight Nov 06 '14 at 12:39
  • Can you elaborate a litle more about `pass the byte array to your model` – Juan Carlos Oropeza May 02 '18 at 02:08
  • @JuanCarlosOropeza in the model you save to the database you would have a property named "File" of type byte[] with a getter/setter. Then call myModel.File = uploadedFile.ToArray() which will copy the byte array into your model then save it to the database (assuming this is done via Entity Framework). – Bil Simser May 25 '18 at 02:17