//用来获取上传的文件
//HttpPostedFileBase files = Request.Files[0];
//获取文件的名字
var fileName = file.FileName;
//将虚拟路径转化为物理路径
var filePath = Server.MapPath("~/images/");
//保存文件内容
file.SaveAs("/images/" + fileName);
前端
<form action="" method="post" enctype="multipart/form-data">
<input id="File1" type="file" name="file" />
<input id="Submit1" type="submit" value="提交" />
</form>
前端
@model IEnumerable<UploadImage.ef.Upload>
@{
ViewBag.Title = "imageShow";
}
<h2>imageShow</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.ImgUrl)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<img src="@Url.Content(item.ImgUrl)" alt="" />
</td>
</tr>
}
</table>
后台
public class UploadController : Controller
{
// GET: Upload
[HttpGet]
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file,string name )
{
//用来获取上传的文件
//HttpPostedFileBase files = Request.Files[0];
//获取文件的名字
var fileName = file.FileName;
//将虚拟路径转化为物理路径
var filePath = Server.MapPath("~/images/");
//保存文件内容
file.SaveAs(Path.Combine(filePath,fileName));
Upload n = new Upload();
n.ImgUrl = "/images/"+fileName;
n.Name = name;
ViewBag.img =n.ImgUrl;
A a = new A();
int i = a.Add(n);
if (i>0)
{
return Redirect("/Upload/imageShow");
}
else
{
return Content("失败");
}
}
public ActionResult imageShow()
{
A N = new A();
return View(N.GetUploads());
}
}
class A
{
public int Add(Upload n)
{
Model1 nn = new Model1();
nn.Upload.Add(n);
int i= nn.SaveChanges();
nn.Dispose();
return i;
}
public List<Upload> GetUploads()
{
Model1 nn = new Model1();
return nn.Upload.ToList();
}
}