@{ ViewBag.Title = "Index"; Layout = ""; } <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="/jquery-1.7.1.js" type="text/javascript"></script> <script src="/ajaxfileupload.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { //$(":button").click(function () { // if ($("#file1").val().length > 0) { // ajaxFileUpload(); // } // else { // alert("請選擇圖片"); // } //}) bindFileChange(); }) function bindFileChange() { $("#file1").change(function () { if ($("#file1").val().length > 0) { ajaxFileUpload(); } }); } function showUploadImgs(data) { if(data.imgList) { $("#dvUploadImgs").empty(); for(var i in data.imgList) { $("#dvUploadImgs").append("<br/><span>" + data.nameList[i] + "</span><br/>"); if (/.(jpg|jpeg|png|gif|bmp)$/.test(data.nameList[i].toLowerCase())) { $("#dvUploadImgs").append("<img id='Img" + i + "' width='500px' src='" + data.imgList[i] + "' /><br/>"); } } } } function ajaxFileUpload() { $.ajaxFileUpload ( { url: '/Home/Upload', //用於文件上傳的服務器端請求地址 type: 'post', data: { Id: '123', name: 'lunis' }, //此參數很是嚴謹,寫錯一個引號都不行 secureuri: false, //通常設置爲false fileElementId: 'file1', //文件上傳空間的id屬性 <input type="file" id="file" name="file" /> dataType: 'json', //返回值類型 通常設置爲json //async: false, success: function (data, status) //服務器成功響應處理函數 { showUploadImgs(data); if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(data.error); } else { alert(data.msg); } } //因爲ajaxFileUpload把原來的file元素替換成新的file元素,因此以前綁定的change事件就失效了,須要從新綁定一下 bindFileChange(); }, error: function (data, status, e)//服務器響應失敗處理函數 { alert(e); } } ) return false; } function checkFile(fileName) { //本身添加的文件後綴名的驗證 return /.(jpg|png|gif|bmp|pdf|doc|docx)$/.test(fileName) ? true : (function () { alert('文件格式僅支持jpg|png|gif|bmp|pdf|doc|docx格式!'); return false; })(); } </script> </head> <body> <p><input type="file" id="file1" name="file" multiple="multiple" accept="image/gif, image/jpeg, image/jpg, image/png, *.pdf"/></p> @*<input type="button" value="上傳" />*@ @*<p><img id="img1" alt="上傳成功啦" src="" /></p>*@ <div id="dvUploadImgs"> </div> </body> </html>
public ActionResult Upload() { NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form; HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files; string imgPath = ""; List<string> imgList = new List<string>(); List<string> nameList = new List<string>(); if (hfc.Count > 0) { int i = 0; while(i<hfc.Count) { imgPath = "/FileUpload/mytest_" + hfc[i].FileName; string PhysicalPath = Server.MapPath(imgPath); hfc[i].SaveAs(PhysicalPath); nameList.Add(hfc[i].FileName); imgList.Add(imgPath); i += 1; } } //注意要寫好後面的第二第三個參數 return Json(new { Id = nvc.Get("Id"), name = nvc.Get("name"), nameList = nameList, imgList = imgList }, "text/html", JsonRequestBehavior.AllowGet); }
//也可使用百度的插件webuploader.js,前端不一樣,後端和上面的同樣,示例以下: @{ ViewBag.Title = "Index"; Layout = ""; } <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script src="/jquery-1.7.1.js" type="text/javascript"></script> <script src="/webuploader.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="/webuploader.css"> <script type="text/javascript"> $(function () { // 初始化Web Uploader var uploader = WebUploader.create({ // 選完文件後,是否自動上傳。 auto: true, // swf文件路徑 swf: '/Uploader.swf', // 文件接收服務端。 server: '/Home/Upload', // 選擇文件的按鈕。可選。 // 內部根據當前運行是建立,多是input元素,也多是flash. pick: '#filePicker', // 只容許選擇圖片文件。 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); // 當有文件添加進來的時候 uploader.on('fileQueued', function (file) { var $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); // $list爲容器jQuery實例 var $list = $("#fileList"); $list.append($li); // 建立縮略圖 // 若是爲非圖片文件,能夠不用調用此方法。 // thumbnailWidth x thumbnailHeight 爲 100 x 100 var thumbnailWidth = 100; var thumbnailHeight = 100; uploader.makeThumb(file, function (error, src) { if (error) { $img.replaceWith('<span>不能預覽</span>'); return; } $img.attr('src', src); }, thumbnailWidth, thumbnailHeight); }); // 文件上傳過程當中建立進度條實時顯示。 uploader.on('uploadProgress', function (file, percentage) { var $li = $('#' + file.id), $percent = $li.find('.progress span'); // 避免重複建立 if (!$percent.length) { $percent = $('<p class="progress"><span></span></p>') .appendTo($li) .find('span'); } $percent.css('width', percentage * 100 + '%'); }); // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。 uploader.on('uploadSuccess', function (file) { $('#' + file.id).addClass('upload-state-done'); }); // 文件上傳失敗,顯示上傳出錯。 uploader.on('uploadError', function (file) { var $li = $('#' + file.id), $error = $li.find('div.error'); // 避免重複建立 if (!$error.length) { $error = $('<div class="error"></div>').appendTo($li); } $error.text('上傳失敗'); }); // 完成上傳完了,成功或者失敗,先刪除進度條。 uploader.on('uploadComplete', function (file) { $('#' + file.id).find('.progress').remove(); }); }); </script> </head> <body> <!--dom結構部分--> <div id="uploader-demo"> <!--用來存放item--> <div id="fileList" class="uploader-list"></div> <div id="filePicker">選擇圖片</div> </div> </body> </html>