ASP.NET-文件上传代码


1

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public ActionResult upload()
  {
      ViewBag.ImageUrl = " " ;
      return View();
  }
  // 模型绑定ModelBinding MVC 框架帮你抽取Request值,转换成视图模型对象
  [HttpPost]
  public ActionResult upload(List<HttpPostedFileBase> files)
  {
      if (files != null )
      {
          List< string > urls = new List< string >();
          foreach (var file in files)
          {
              if (file != null && file.ContentLength > 0)
              {
                  // 1.获取文件名
                  string fileName=Path.GetFileName(file.FileName);
                  string timeName = DateTime.Now.Ticks.ToString();
                  // 2.保存文件到网站文件夹
                  string localpath=Server.MapPath( "~/UploadFile/" );
                  string tempName = timeName + fileName;
                  string fullpath = localpath + tempName;
                  file.SaveAs(fullpath);
                  // 传递到视图图片路径,显示图片
                  string temp = "/UploadFile/" + tempName;
                  urls.Add(temp);
                  //ViewBag.ImageUrl = fullpath;
                  // 3.保存的路径存入数据库的地址字段
              }
 
          }
          ViewBag.urls = urls;
      }
      return View();
  }

后台代码主要使用HttpPostedFileBase对象来操作file这个流对象


前台主要使用form表单工具来提交文件

1
2
3
4
5
6
7
8
9
10
11
12
13
@ using (Html.BeginForm( "upload" , "Order" , FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <input type= "file" id= "files" name= "files"  multiple= "multiple" />
     <input type= "submit" value= "上传图片" class = "btn btn-default form-control" />
}
 
@ if (ViewBag.urls != null )
{
     foreach (var url in ViewBag.urls)
     {
         <img style= "width:300px;" src= "@url" />
     }
}










转载于:https://www.cnblogs.com/weloveshare/p/5314247.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值