Uploading Files into Database with ASP.NET MVC

前端 未结 1 636
独厮守ぢ
独厮守ぢ 2020-11-27 05:27

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 tri

1条回答
  •  無奈伤痛
    2020-11-27 05:35

    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" }))
    {
        
    @Html.LabelFor(x => x.File) @Html.TextBoxFor(x => x.File, new { type = "file" }) @Html.ValidationMessageFor(x => x.File)
    }

    0 讨论(0)
提交回复
热议问题