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

寻技术 Html/CSS / ASP.NET编程 2023年07月11日 98

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");
        }

 

关闭

用微信“扫一扫”