Google Code Prettify

[MVC]多檔上傳

View


修改 \Views\Shared\_Layout.cshtml ,增加下列連接資料:

@Html.ActionLink("檔案上傳", "Index", "FileUpload", new { area = "" }, null)



增加 \Views\FileUpload\Index.cshtml

@model WebServiceTest.Models.UploadFileInfo

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<div>@ViewBag.Message</div>
@using(Html.BeginForm("Index", "FileUpload", 
    new { ReturnUrl = ViewBag.ReturnUrl }, 
    FormMethod.Post, new { @class = "form-inline", role = "form", enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()
    <input type="file" name="FileName" id="FileName" multiple="multiple" />
    <img id="image1" src="" />
    <br /><br />
    <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
}

@section  scripts{
    <script>
        $("#FileName").change(function () {
            InputLoadImageToBindImageElement(this, $('#image1'));
        });
        function InputLoadImageToBindImageElement(inputEl, imgEl) {
            if (inputEl.files && inputEl.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $(imgEl).attr('src', e.target.result);
                }
                reader.readAsDataURL(inputEl.files[0]);
            }
        }
    </script>
}




Controller


增加 \ControllersForUser\FileUploadController.cs

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

using WebServiceTest.Models;

namespace WebServiceTest.ControllersForUser {
    public class FileUploadController : Controller {
        // GET: FileUpload
        public ActionResult Index() {
            UploadFileInfo uploadFileInfo = new UploadFileInfo();
            return View(uploadFileInfo);
        }
        [HttpPost]
        public ActionResult Index(UploadFileInfo uploadFileInfo) {
            foreach(string upload in Request.Files) {
                if(!(Request.Files[upload] != null && Request.Files[upload].ContentLength > 0))
                    continue;
                int memUsage_baseline_id = 0;
                int timingComp_baseline_id = 0;
                if(upload == "FileUploadMemoryUsage" || upload == "FileUploadResultsComparison")
                    if(upload == "FileUploadMemoryUsage")
                        if(Request.Params["memUsage_project"] == null || Request.Params["memUsage_project"] == "")
                            ModelState.AddModelError("Project", "Please Select Project for Memory Usage");
                        else
                            memUsage_baseline_id = int.Parse(Request.Params["memUsage_project"]);
                    else
                        if(Request.Params["resultsComp_project"] == null || Request.Params["resultsComp_project"] == "")
                        ModelState.AddModelError("Project", "Please Select Project for Timing Comparison");
                    else
                        timingComp_baseline_id = int.Parse(Request.Params["resultsComp_project"]);
                HttpPostedFileBase file = Request.Files[upload];
                if(ModelState.IsValid)
                    if(file == null)
                        ModelState.AddModelError("File", "Please Upload Your file");
                    else if(file.ContentLength > 0) {
                        int MaxContentLength = 1024 * 1024 * 3; //3 MB
                        string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
                        if(!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                            ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                        else if(file.ContentLength > MaxContentLength)
                            ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                        else {
                            if(!Directory.Exists(Server.MapPath("~/Upload")))
                                Directory.CreateDirectory(Server.MapPath("~/Upload"));
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                            file.SaveAs(path);
                            ModelState.Clear();
                            //ViewBag.Message = "File uploaded successfully";
                            TempData["message"] = "File uploaded successfully";
                        }
                    }
            }
            return View();
        }
    }
}