惯看花开花又谢,却怕缘起缘又灭…….成为你的护身符 shuangjian_wei@qq.com

.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(); }

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

posted @ 2016-01-20 16:02  护身符  阅读(454)  评论(0编辑  收藏  举报
宝剑锋从磨砺出 梅花香自苦寒来!
联系我: shuangjian_wei@qq.com