新增了一個Controller(UploadFileController),橘色區塊是自己加入的內容,至於一些上傳的檢查在這就不討論

IEnumerable<HttpPostedFileBase> files 是用來接View傳過來的資料,再使用foreach去拆成一個個

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UploadFileTest.Controllers
{
    public class UploadFileController : Controller
    {
        // GET: UploadFile
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
        {
            if (files != null)
            {
                foreach (var file in files)
                {
                    if (file != null)
                    {
                        string fileName = Path.GetFileName(file.FileName);
                        string path = Path.Combine(Server.MapPath("~/Files/"), fileName);
                        file.SaveAs(path);
                        TempData["message"] = "上傳成功";
                    }
                    else
                    {
                        TempData["message"] = "請先選檔案";
                    }
                }
            }
            return RedirectToAction("Index");
        }
    }
}

 

新增了一個View,橘色部分是自己加入的內容,基本上就是使用javascript去增加輸入檔案的數量

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@Html.Raw(TempData["message"])
<div>
    @using (Html.BeginForm("Index", "UploadFile", FormMethod.Post, new {enctype = "multipart/form-data"}))
    {
        <div class="multiUpload">
            <input type="file" id="file" name="files"/>
        </div>
        <div>
            <button>增加上傳檔案</button>
            <input type="submit" value="上傳檔案"/>
        </div>
    }
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function() {
        $('button').on('click', function() {
            $('.multiUpload').append("<input type='file' id='file' name='files'/>");
            event.preventDefault();
        });
    })
</script>

arrow
arrow

    痞客興 發表在 痞客邦 留言(0) 人氣()