上传文件与ASP.NET MVC数据库 [英] Uploading Files into Database with ASP.NET MVC
本文介绍了上传文件与ASP.NET MVC数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想给我的形式为用户在设备上载文件,并保存在数据库中。
这是如何在ASP.NET MVC中完成的。
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.
在我的模型类写什么数据类型。我与试图字节[]
,但脚手架过程中的解决方案无法生成相应信息查看它相应的HTML。
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?
推荐答案
您可以使用字节[]
你的模型和一个 HttpPostedFileBase
您的视图模型。例如:
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; }
}
和则:
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>
}
这篇关于上传文件与ASP.NET MVC数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文