1. 程式人生 > >.net mvc異步上傳文件

.net mvc異步上傳文件

edi ssa doctype 上傳文件 執行 成功 dir ice viewbag

第一種方式:需要引入jquery.form.min.js  

jquery.form.min.js下載地址

鏈接:https://pan.baidu.com/s/1HQbd-1cbwmnPdOJL0oj8zA
提取碼:j0hx
復制這段內容後打開百度網盤手機App,操作更方便哦

技術分享圖片
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <script src="
~/Scripts/UpLoadFile/jquery-1.8.2.min.js"></script> <script src="~/Scripts/UpLoadFile/jquery.form.min.js"></script> </head> <body> <div> <h3>mvc異步上傳文件</h3> @using (Ajax.BeginForm("FileloadAction", "UpLoad", new AjaxOptions { Confirm
= "確認上傳嗎?", HttpMethod = "post", OnSuccess = "func", }, new { enctype = "multipart/form-data", id = "fileForm" })) { <input type="file" name="Filedata" value="" accept=".xls,.docx,.doc,.txt,.pdf" /> @*<button type="submit"
>異步上傳</button>*@ <button type="button">異步上傳</button> } </div> </body> </html> <script> //當按鈕被點擊時執行異步提交 $("button[type=button]").click(() => { //異步提交 $("#fileForm").ajaxSubmit({ url: "@Url.Action("FileloadAction", "UpLoad")", type: "post", success: data => { alert(data); }, error: () => { alert("出錯了"); } }); }); </script>
Indx視圖代碼

控制器代碼:

技術分享圖片
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HomeWorkSystem.Controllers
{
    public class UpLoadController : Controller
    {
        
        public ActionResult Index()
        {
          
            return View();
        }
              
        public ActionResult FileloadAction(IEnumerable<HttpPostedFileBase> Filedata)
        {
            if (Filedata == null || Filedata.Count() == 0 || Filedata.ToList()[0] == null)
            {
                ViewBag.ErrorMessage = "Please select a file!!";
                return Content("請選擇文件~~~");
            }
            string filePath = string.Empty;
            string rootFilePath = string.Empty;
            string fileName = string.Empty;
            //多文件上傳
            foreach (HttpPostedFileBase file in Filedata)
            {
                string jsonUrl = "UpLoadHomeWork/";
                string Url_ClassName = "信息16-1/";
                string Url_LessName = "安卓移動";
                rootFilePath = AppDomain.CurrentDomain.BaseDirectory + jsonUrl + Url_ClassName + Url_LessName;
                //檢查目錄是否存在:不存在則創建
                if (!Directory.Exists(rootFilePath))
                {
                    Directory.CreateDirectory(rootFilePath);
                }
                //對錄入上傳文件的名字
                string extName = Path.GetExtension(file.FileName);
                string C_Name = "信息16-1";
                string T_Title = "JavaWeb";
                fileName = C_Name + T_Title + extName;
                //將文件上傳到rootFilePath路徑下
                file.SaveAs(Path.Combine(rootFilePath, fileName));
            }
            return Content(fileName+"上傳成功");
        }
       

    }
}
UpLoadController

.net mvc異步上傳文件