• 用Html5与Asp.net MVC上传多个文件


    html:

            <form action="/home/upload" method="post" enctype="multipart/form-data">
                <input type="file"  name="files" multiple/>
                <input type="submit" value="提交" />
            </form>

    文件file 的name属性必填。

    ActionResult:

     [HttpPost]
            public ActionResult Upload(HttpPostedFileBase[] files)
            {
                var path = Server.MapPath("/File");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                foreach (HttpPostedFileBase item in files)
                {
                    item.SaveAs(Path.Combine(path, item.FileName));
                }
                return Content("ok");
            }

    H5让我们轻松实现文件上传.

    如果异步,代码如下

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    </head>
    <body>
        <div>
            <form id="formtable" enctype="multipart/form-data">
                <input type="file" id="files" name="files" multiple />
                <input type="button" id="btnok" value="提交" />
            </form>
        </div>
        <script>
            $("#btnok").click(function () {
                var formdata = new FormData(document.getElementById("formtable"));
                $.ajax({
                    url: "/home/upload",
                    data: formdata,
                    type: 'post',
                    datatype: 'json',
                    // XMLHttpRequest会对 formdata 进行正确的处理
                    processData: false,
                    //必须false才会自动加上正确Content-Type
                    contentType: false,
                    success: function (data) { alert(data); }
                })
            });
        </script>
    </body>
    </html>
    public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Upload(HttpPostedFileBase[] files)
            {
                var path = Server.MapPath("/File");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                foreach (HttpPostedFileBase item in files)
                {
                    item.SaveAs(Path.Combine(path, item.FileName));
                }
                return Content("ok");
            }
  • 相关阅读:
    SQL学习
    设计模式学习之简单工厂
    c#读写操作3
    SQL存储过程学习
    c# xml的读写
    SQL存储过程实例
    存储过程分页
    搞双显示器
    转:用药的七种心理误区
    lp提了一个非常让偶非常郁闷的要求……
  • 原文地址:https://www.cnblogs.com/lunawzh/p/9326619.html
Copyright © 2020-2023  润新知