.net MVC 简单图片上传

主要完成的是在网页上 上传一张图片到服务器

我搜出来的上传文件代码都特别复杂,对于初学者来说,先解决能上传的问题才最重要,并不需要特别多的功能,仅适合不会上传的初学者,大神请绕路,错误请指出,谢谢

view内容由于是从项目中直接拷贝出来的,需要整理才可使用,看关键的就好了):

  图片:

  代码:

            <!--这里的method 和 enctype 要照写,不要忘写或写错-->
      <form action="ManageIcon" method="post" enctype="multipart/form-data" class="form-horizontal" role="form"> <div class="col-sm-6"> <label class="text-warning">请选择尺寸为160*160的图片</label> <div class="row"> <div class="col-md-10"> <a href="#" class="thumbnail"> @*<img src="@ViewBag.LoginedUser.Icon" class="img-responsive" alt="Cinque Terre" style="height:160px;width:160px">*@ </a> </div> </div> </div> <div class="col-sm-6">
              <!--注意这里,这里的input在后台很关键,下面会有提示--> <input name="filename" id="filename" type="file"/> </div> <div class="col-sm-12" style="margin-top:30px"> <button type="submit" id="s" class="btn btn-primary" style="margin-left:30px">保存</button> <button type="button" class="btn btn-default" style="margin-left:30px">取消</button> </div> </form>

项目目录:

控制器代码

  [HttpPost]
        public ActionResult ManageIcon(IEnumerable <HttpPostedFileBase>filename)
        {
            foreach (var file in filename)
            {
          //重命名,图片在服务器上的名字
string name = Path.GetFileName(file.FileName); string[] la = name.Split('.'); string nameNew = DateTime.Now.ToFileTimeUtc().ToString(); nameNew += "."+la[la.Length];

          //获取项目根目录 string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
          //这里获取前台传来的流信息
          
using (Stream inputstream = file.InputStream) { //在服务上创建文件流,事先已经在根目录创建了\Images\Icons文件夹
            FileStream fs
= new FileStream(path+"Images\\Icons\\"+nameNew,FileMode.CreateNew,FileAccess.ReadWrite);   
            //文件读写
            byte[] buffer=new byte[1024];    int a = inputstream.Read(buffer,0,buffer.Length); while(a!=0){ fs.Write(buffer,0,buffer.Length); a = inputstream.Read(buffer, 0, buffer.Length); }

            //不写这里可能会上传不完整,如下图 fs.Flush(); fs.Close(); } }
return View(); }

 示例图(第二张没有上传完整):

转载于:https://www.cnblogs.com/Alan-Wei/p/5145386.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值