这是我的观点
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>File :</td>
<td><input type="file" name="File" id="file" /> </td>
</tr>
<tr>
<td><input type="submit" name="submit" value="upload" /></td>
</tr>
这是我的控制器
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Picture picture)
{
if (picture.File.ContentLength > 0)
{
var fileName = Path.GetFileName(picture.File.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
picture.File.SaveAs(path);
}
return RedirectToAction("Index");
}
and Model:
namespace FileUpload.Models
{
public class Picture
{
public HttpPostedFileBase File { get; set; }
}
此代码帮助我将图像保存在我的MVC项目根Image文件夹中,但我想将其保存到我的数据库中。我尝试过很多教程,但还没有成功......“ 我实际上正在制作学生表格,每个学生都会注册他的照片。
答案 0 :(得分:1)
将图像转换为字节,然后将其存储在数据库中
[HttpPost]
public ActionResult Index(Picture picture)
{
byte[] Image;
if (Request.Files["files"] != null)
{
using (var binaryReader = new BinaryReader(Request.Files["file"].InputStream))
{
Image = binaryReader.ReadBytes(Request.Files["files"].ContentLength);
}
Picture.File =Image;
}
return RedirectToAction("Index");
}
模型
public class Picture
{
public byte[] File { get; set; }
}
显示图像的视图
if (Model.File != null)
{
string imageBase64 = Convert.ToBase64String(Model.File );
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="@imageSrc" width="100" height="100" />
}