文章詳情頁
ASP.NET MVC使用JSAjaxFileUploader插件實現(xiàn)單文件上傳
瀏覽:101日期:2022-06-08 10:48:41
先看效果:
- 上傳文件顯示進度條:
- 停止上傳按鈕和關(guān)閉縮略圖按鈕:
- 限制上傳文件的類型:
- 限制上傳文件的尺寸:
- 上傳成功后顯示縮略圖、文件名以及回傳信息:
- 點擊界面上的刪除按鈕,界面刪除,同步刪除文件夾中文件。
- 重新上傳文件,界面刪除,同步刪除文件夾中文件,并界面顯示新的縮略圖、文件名等。
HomeController
由于需要把保存到文件夾文件的路徑、文件名等回傳給界面,所以需要一個類,專門負責(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; } }
把上傳的文件名改成以時間命名的格式,并保存到文件夾,再把回傳信息以json形式傳遞給視圖。關(guān)于刪除,需要接收來自視圖的文件名參數(shù)。
#region 上傳單個文件 //顯示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>/// 檢查是否要創(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
前臺視圖主要做如下幾件事:
- 每次上傳之前檢查表格中是否有數(shù)據(jù),如果有,實施界面刪除并同步刪除文件夾中的文件
- 上傳成功動態(tài)創(chuàng)建表格行顯示縮略圖、文件名和刪除按鈕
- 點擊刪除按鈕實施界面刪除并同步刪除文件夾中的文件
由于表格行是動態(tài)生成的,需要對刪除按鈕以"冒泡"的方式注冊事件: $('#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);} }); //點擊刪除鏈接刪除剛上傳圖片 $("#tbl").on("click", ".delImg", function () {deleteImg();//window.location.reload(); });}); //刪除圖片方法:點擊刪除鏈接或上傳新圖片刪除原先圖片用到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("出錯了 "" + jqXhr.status + "" (狀態(tài): "" + textStatus + "", 錯誤為: "" + 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>
另外:需要刪除源js文件中input元素的multiple屬性,使之只能接收單個文件。
本篇源碼在github
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
標(biāo)簽:
ASP.NET
相關(guān)文章:
1. ASP.NET MVC視圖頁使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解2. ASP.NET MVC使用Boostrap實現(xiàn)產(chǎn)品展示、查詢、排序、分頁3. ASP.NET MVC實現(xiàn)城市或車型三級聯(lián)動4. ASP.NET MVC實現(xiàn)橫向展示購物車5. ASP.NET MVC實現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片6. ASP.NET MVC實現(xiàn)區(qū)域或城市選擇7. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法8. 使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移9. ASP.NET MVC增加一條記錄同時添加N條集合屬性所對應(yīng)的個體10. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字
排行榜
