MVC中的图片上传

//用来获取上传的文件
            //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();
            
        }
 
    }
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值