asp.net mvc動態生成file控件批量上傳文件

頁面代碼:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章