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>
}
Nguồn
2013-02-27 07:31:58
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