文章詳情頁
ASP.NET MVC使用JSAjaxFileUploader插件實(shí)現(xiàn)單文件上傳
瀏覽:127日期:2022-06-08 10:48:41
先看效果:
- 上傳文件顯示進(jìn)度條:
- 停止上傳按鈕和關(guān)閉縮略圖按鈕:
- 限制上傳文件的類型:
- 限制上傳文件的尺寸:
- 上傳成功后顯示縮略圖、文件名以及回傳信息:
- 點(diǎn)擊界面上的刪除按鈕,界面刪除,同步刪除文件夾中文件。
- 重新上傳文件,界面刪除,同步刪除文件夾中文件,并界面顯示新的縮略圖、文件名等。
HomeController
由于需要把保存到文件夾文件的路徑、文件名等回傳給界面,所以需要一個(gè)類,專門負(fù)責(zé)回傳給客戶端所需要的信息。
public class UploadFileResult {public string FileName { get; set; }public int Length { get; set; }public string Type { get; set; }public bool IsValid { get; set; }public string Message { get; set; }public string FilePath { get; set; } }
把上傳的文件名改成以時(shí)間命名的格式,并保存到文件夾,再把回傳信息以json形式傳遞給視圖。關(guān)于刪除,需要接收來自視圖的文件名參數(shù)。
#region 上傳單個(gè)文件 //顯示public ActionResult Index(){ return View();} //接收上傳[HttpPost]public ActionResult UploadFile(){ List<UploadFileResult> results = new List<UploadFileResult>(); foreach (string file in Request.Files) {HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;if (hpf.ContentLength == 0 || hpf == null){ continue;} var fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + hpf.FileName.Substring(hpf.FileName.LastIndexOf("."));string pathForSaving = Server.MapPath("~/AjaxUpload");if (this.CreateFolderIfNeeded(pathForSaving)){ hpf.SaveAs(Path.Combine(pathForSaving, fileName)); results.Add(new UploadFileResult() {FilePath = Url.Content(String.Format("~/AjaxUpload/{0}", fileName)),FileName = fileName,IsValid = true,Length = hpf.ContentLength,Message = "上傳成功",Type = hpf.ContentType });} } return Json(new {name = results[0].FileName,type = results[0].Type,size = string.Format("{0} bytes", results[0].Length),path = results[0].FilePath,msg = results[0].Message });} #region 共用方法/// <summary>/// 檢查是否要?jiǎng)?chuàng)建上傳文件夾,如果沒有就創(chuàng)建/// </summary>/// <param name="path">路徑</param>/// <returns></returns>private bool CreateFolderIfNeeded(string path){ bool result = true; if (!Directory.Exists(path)) {try{ Directory.CreateDirectory(path);}catch (Exception){ //TODO:處理異常 result = false;} } return result;} //根據(jù)文件名稱刪除文件[HttpPost]public ActionResult DeleteFileByName(string name){ string pathForSaving = Server.MapPath("~/AjaxUpload"); System.IO.File.Delete(Path.Combine(pathForSaving, name)); return Json(new {msg = true });}#endregion
Home/Index.cshml
前臺(tái)視圖主要做如下幾件事:
- 每次上傳之前檢查表格中是否有數(shù)據(jù),如果有,實(shí)施界面刪除并同步刪除文件夾中的文件
- 上傳成功動(dòng)態(tài)創(chuàng)建表格行顯示縮略圖、文件名和刪除按鈕
- 點(diǎn)擊刪除按鈕實(shí)施界面刪除并同步刪除文件夾中的文件
由于表格行是動(dòng)態(tài)生成的,需要對(duì)刪除按鈕以"冒泡"的方式注冊(cè)事件: $('#tb').on("click", ".delImg", function ()
<html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link href="~/Content/JSAjaxFileUploader/JQuery.JSAjaxFileUploader.css" rel="external nofollow" rel="stylesheet" /> <script src="~/Scripts/jquery-1.10.2.js"></script> <script src="~/Scripts/JSAjaxFileUploader/JQuery.JSAjaxFileUploaderSingle.js"></script> <style type="text/css">#tb table{ border-collapse: collapse; width: 600px; } #tb td { text-align: center; padding-top: 5px; width: 25%;} #tb tr { background-color: #E3E3E3; line-height: 35px;} .showImg { width: 50px; height: 50px;} </style> <script type="text/javascript">$(function () { //隱藏顯示圖片的表格 $("#tbl").hide(); $("#testId").JSAjaxFileUploader({uploadUrl: "@Url.Action("UploadFile","Home")",inputText: "選擇上傳文件",//fileName: "photo",maxFileSize: 512, //Max 500 KB file 1kb=1024字節(jié)allowExt: "gif|jpg|jpeg|png",zoomPreview: false,zoomWidth: 360,zoomHeight: 360,beforesend: function (file) { if ($(".imgName").text() != "") {deleteImg();$("#tbl").hide(); }},success: function (data) { $(".file_name").html(data.name); $(".file_type").html(data.type); $(".file_size").html(data.size); $(".file_path").html(data.path); $(".file_msg").html(data.msg); createTableTr(); $("#tbl").show(); $(".showImg").attr("src", data.path); $(".imgName").text(data.name);},error: function (data) { alert(data.msg);} }); //點(diǎn)擊刪除鏈接刪除剛上傳圖片 $("#tbl").on("click", ".delImg", function () {deleteImg();//window.location.reload(); });}); //刪除圖片方法:點(diǎn)擊刪除鏈接或上傳新圖片刪除原先圖片用到function deleteImg() { $.ajax({cache: false,url: "@Url.Action("DeleteFileByName", "Home")",type: "POST",data: { name: $(".imgName").text() },success: function (data) { if (data.msg) {//alert("圖片刪除成功");$(".delImg").parent().parent().remove(); }},error: function (jqXhr, textStatus, errorThrown) { alert("出錯(cuò)了 "" + jqXhr.status + "" (狀態(tài): "" + textStatus + "", 錯(cuò)誤為: "" + errorThrown + "")");} });} //創(chuàng)建表格function createTableTr() { var table = $("#tbl"); table.append("<tr><td><img class="showImg"/></td><td colspan="2"><span class="imgName"></span></td><td><a class="delImg" href="javascript:void(0)">刪除</a></td></tr>");} </script></head><body> <div id="testId"></div> <div id="tb"><table id="tbl"> <tbody> </tbody></table> </div><div></div><br /><div></div><br /><div></div><br /><div></div><br /><div></div></body></html>
另外:需要?jiǎng)h除源js文件中input元素的multiple屬性,使之只能接收單個(gè)文件。
本篇源碼在github
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
標(biāo)簽:
ASP.NET
相關(guān)文章:
1. ASP.NET MVC實(shí)現(xiàn)本地化和全球化2. ASP.NET MVC實(shí)現(xiàn)單個(gè)圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片3. ASP.NET MVC使用jQuery的Load方法加載靜態(tài)頁面及注意事項(xiàng)4. ASP.NET MVC使用異步Action的方法5. ASP.NET MVC使用正則表達(dá)式驗(yàn)證手機(jī)號(hào)碼6. ASP.NET MVC實(shí)現(xiàn)城市或車型三級(jí)聯(lián)動(dòng)7. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條8. ASP.NET MVC使用Quartz.NET執(zhí)行定時(shí)任務(wù)9. ASP.NET MVC增加一條記錄同時(shí)添加N條集合屬性所對(duì)應(yīng)的個(gè)體10. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容
排行榜
