• MVC上传文件


    ASP.NET MVC上传文件是必段撑握的知识。加强训练才是。
    以前Insus.NET曾使用第三方MyAjaxForm.js :http://www.cnblogs.com/insus/p/3785484.html 

    或者是jQuery的Uploadify组件:http://www.cnblogs.com/insus/p/3590907.html 

    还有一篇可以参考的,VS标准标签input 的type="file":http://www.cnblogs.com/insus/p/4040352.html

    今天还是参考上面最后篇,实现上传单一或是多个文件,不过语法有所改变:
    创建一个控制,一个视图操作,一个操作是处理上传文件方法:



    代码:

    public ActionResult UploadFile()
            {            
                return View();
            }
    
            [HttpPost]
            public ActionResult ProcessUploadFiles(IEnumerable<HttpPostedFileBase> filename)
            {
                foreach (var file in filename)
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/Temp"), fileName);
                        file.SaveAs(path);
                    }
                }
                return RedirectToAction("UploadFile");
            }
    View Code


    再来看看视图的实现:

    上面的filename名字需要匹配。如果不一样,在运行时会呈现异常,参考下面动画演示:



    如果需要同时上传多个文件,我们只管拉多几个:

    <input type="file" name="filename" id="file1" />
    View Code


    如同时上传3个:

  • 相关阅读:
    1211.分割平衡字符串
    1282.用户分组
    分模块配置
    Spring Bean相关配置
    Spring IOC是什么
    Spring简介
    小黄衫感想
    团队展示
    原型设计
    结对作业
  • 原文地址:https://www.cnblogs.com/insus/p/4609843.html
Copyright © 2020-2023  润新知