关闭

asp.net mvc动态生成file控件批量上传文件

标签: fileasp.netmvcuploadpathinput
587人阅读 评论(0) 收藏 举报
分类:

页面代码:

<body>
    <div>
        <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
           { %>
        <div id="FileList">
            <div>
                <input type="file" id="file0" name="file0" />
            </div>
        </div>
        <p>
            <a onclick="AddFile();" style="color: Blue; text-decoration: underline">新增文件</a></p>
        <p>
            <input type="submit" value="上传" /></p>
        <%} %>
    </div>
</body>

 

js代码:(根据用户自动生成上传控件)

        var index = 1;
        function AddFile() {
            var ul = document.getElementById("FileList");
            var inputDiv = document.createElement("div");
            inputDiv.setAttribute("Id", "div" + index);
            var file = document.createElement("input");
            file.setAttribute("type", "file");
            file.setAttribute("id", "file" + index);
            file.setAttribute("name", "file" + index);
            var btnDel = document.createElement("input");
            btnDel.setAttribute("type", "button");
            btnDel.setAttribute("value", "删除");
            btnDel.setAttribute("Id", index);
            btnDel.onclick = function() {
                inputDiv.removeChild(file);
                inputDiv.removeChild(btnDel);
                ul.removeChild(inputDiv);
            }
            inputDiv.appendChild(file);
            inputDiv.appendChild(btnDel);
            ul.appendChild(inputDiv);
            index++;
        }

 

Controller的代码:

       [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Upload()
        {
            foreach (string item in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                if (file==null&&file.ContentLength == 0)
                    continue;
                //判断Upload文件夹是否存在,不存在就创建
                string path = Server.MapPath("..//Upload");
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                path = AppDomain.CurrentDomain.BaseDirectory + "Upload/";
                //获取上传的文件名
                string fileName = Path.GetFileName(file.FileName);
                //限制上传文件的类型
                if (Path.GetExtension(fileName)!=".doc")
                {
                    return Content("<script>alert('只能上传后缀名为.doc的文件');</script>");
                }
                //上传
                file.SaveAs(Path.Combine(path,fileName));
            }
            return Content("<script>alert('上传文件成功');window.history.back();</script>");
        }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3991次
    • 积分:81
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条