2013-02-27 41 views
10

Tôi muốn cung cấp cho một cơ sở trên biểu mẫu của tôi để người dùng tải tệp lên và lưu vào Cơ sở dữ liệu. Cách này được thực hiện trong ASP.NET MVC.Tải tệp lên cơ sở dữ liệu với ASP.NET MVC

Loại dữ liệu nào cần ghi trong Lớp mô hình của tôi. Tôi đã thử với Byte[], nhưng trong giàn giáo giải pháp không thể tạo HTML thích hợp cho nó trong Chế độ xem tương ứng.

Các trường hợp này được xử lý như thế nào?

Trả lời

31

Bạn có thể sử dụng byte[] trên mô hình của mình và HttpPostedFileBase trên kiểu xem của bạn. Ví dụ:

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

và sau đó:

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

và cuối cùng là theo quan điểm của bạn:

@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> 
} 
+0

Hi, đây là tuyệt vời, nhưng như một Noob tuyệt đối, nơi sẽ là nơi tốt nhất để lưu trữ các tệp, ví dụ: tôi chỉ muốn cho phép quản trị viên trang web tải lên tệp (tệp .exe ứng dụng) mà người dùng có thể tải xuống? – MoonKnight

Các vấn đề liên quan