代码改变世界

MVC 图片上传小试笔记

2013-04-25 16:13  stoneniqiu  阅读(503)  评论(0编辑  收藏  举报

说明:现在jquery上传图片的插件很多了,但还是想弄清楚下MVC 图片是怎么传上去的。结果反馈,效果还需要改善。

 1.在View中还是用beginform                                                                                           

   再加上 一个file,一个submit,用post的方式将file传递过, 表单标签中设置enctype="multipart/form-data"来确保匿名上载文件的正确编码。默认情况下的form是不能用来上传的。

@using (Html.BeginForm("Upload","Home",FormMethod.Post,new {enctype="multipart/form-data"}))
{
    
        <span id="ss"></span>
     <input type="file" name="file"  required="required"  />
     <input type="submit" name="subt" value="Upload File"/>
}

生成的页面的HTML如下,

<form action="/Home/Upload" enctype="multipart/form-data" method="post"> 
  <input type="file" name="file"  required="required"  />
  <input type="submit" name="subt" value="Upload File"/>
</form>

 

2.控制器中的方法                                                                                                              

  这里主要是获取文件名、文件地址、判断扩展名,再保存。但这里对结果的反馈还不够好,return view 会造成刷新。在content目录下创建UploadFiles文件夹

拿掉扩展名,或者改变 就可以传其他的文件了

View Code
  public ActionResult Upload()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file != null)
            {
                var fileName = file.FileName;//Path.GetExtension() 也许可以解决这个问题,先不管了。
                if (fileName.LastIndexOf("\\", System.StringComparison.Ordinal) > -1)//在不同浏览器下,filename有时候指的是文件名,有时候指的是全路径,所有这里要要统一。
                {
                    fileName = fileName.Substring(fileName.LastIndexOf("\\", System.StringComparison.Ordinal) + 1);//IndexOf 有时候会受到特殊字符的影响而判断错误。加上这个就纠正了。
                }
                 var image = Path.GetExtension(fileName.ToLower());
                  if (image != ".bmp" && image != ".png" && image != ".gif" && image != ".jpg")// 这里你自己加入其他图片格式,最好全部转化为大写再判断,我就偷懒了
                {
                      return View("Index"); //  
                }
             
                var filepath = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), fileName);
                //string filename = file.FileName;
                //string savePath = Server.MapPath(("../Content/UploadFiles/") + filename);
               file.SaveAs(filepath);
            }
            return View("Index");

        }
      

 

 

3. 图片显示                                                                                                                  

     这里主要是用Directory.GetFiles 获取到文件的信息后显示就行了 

   public List<FileDescription> GetAllFileDescription()
        {
            string uploadFolder = Server.MapPath("../Content/UploadFiles");
            string[] files = Directory.GetFiles(uploadFolder);//获取多个类型格式的文件
         
            var fileDescriptions = new List<FileDescription>();
            foreach (var file in files)
            {
                var fileInfo=new FileInfo(file);
                fileDescriptions.Add(
                    new FileDescription
                        {
                            Name = fileInfo.Name,
                            Size = (float)fileInfo.Length/1024,//这里得到的是k
                            WebPath = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), fileInfo.Name),
                            DateCreated = fileInfo.CreationTime
                        }
                    );
            }
            return fileDescriptions;


        }
 

这里的view就是自动生成的强类型视图(部分),只是自己再加入   <img src="http://www.cnblogs.com/Content/UploadFiles/@item.Name" />  

 还需要改进在一个页面预览,反馈上传结果而不刷新