標籤:des style class blog code java
在View視圖中:
<link href="/Scripts/uploadify-v3.2.1/uploadify.css" rel="stylesheet" type="text/css" /><script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script><script src="/Scripts/uploadify-v3.2.1/jquery.uploadify.js" type="text/javascript"></script><script src="/Scripts/uploadify-v3.2.1/swfobject.js"></script><script type="text/javascript"> $(document).ready(function () { $(‘#file_upload‘).uploadify({ ‘buttonText‘: ‘選擇上傳檔案‘, ‘queueID‘: ‘fileQueue‘,//指定上傳進度條在哪裡顯示 ‘swf‘: ‘@Url.Content("~/Scripts/uploadify-v3.2.1/uploadify.swf?ver=‘+Math.random()+‘")‘, ‘uploader‘: ‘/Home/Upload‘, ‘removeCompleted‘: true, ‘checkExisting‘: true, ‘fileTypeDesc‘: ‘上傳的檔案類型‘, ‘fileTypeExts‘: ‘*.jpg;*.png;*.gif‘, ‘fileSizeLimit‘: ‘1024kb‘, ‘auto‘: false, ‘multi‘: false, ‘queueSizeLimit‘: 1, //一個隊列上傳檔案數限制 ‘uploadLimit‘: 1, //允許上傳的最多張數 ‘height‘: 30, ‘width‘: 80, ‘onUploadSuccess‘: function (file, data, response) { var obj = jQuery.parseJSON(data); //把返回的Json序列轉化為obj對象 if (obj.Success) { $(‘#input‘).val(obj.FilePath); $(‘#upsucc‘).text(‘上傳成功!‘); } else alert(obj.Message); } }); });
<tr> <th>@Html.LabelFor(model=>model.Url)</th> <td> <input type="file" class="file_upload" id="file_upload"/> <div id="fileQueue"></div> <a href="javascript:$(‘#file_upload‘).uploadify(‘upload‘);">上傳</a><span id="upsucc" style="color:red"></span> @Html.TextBoxFor(m => m.Url, new { id="input",@style="display:none"}) </> </tr>
Controller中
[HttpPost] public JsonResult Upload(HttpPostedFileBase fileData) { if (fileData != null) { try { // 檔案上傳後的儲存路徑 string filePath = Server.MapPath("~/Uploads/"); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } string fileName = Path.GetFileName(fileData.FileName);// 原始檔案名稱 string fileExtension = Path.GetExtension(fileName); // 副檔名 string saveName = Guid.NewGuid().ToString() + fileExtension; // 儲存檔案名稱 int filesize = fileData.ContentLength / 1024; if (filesize > 1024 || filesize <= 2 || (fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".gif")) { return Json(new { Success = false, Message = "上傳失敗!\r請上傳jpg/png格式圖片,檔案大小不要超過1MB" }, JsonRequestBehavior.AllowGet); } else { fileData.SaveAs(filePath + saveName); return Json(new { Success = true, FilePath = "/Uploads/" + saveName }); } } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); } } else { return Json(new { Success = false, Message = "請選擇要上傳的檔案!" }, JsonRequestBehavior.AllowGet); } }
在後台應用中會遇到HTTP 302的錯誤 這是因為應用外掛程式的過程中 沒有了session 所以public JsonResult Upload(HttpPostedFileBase fileData) 最好放到一個沒有存取權限的Controller中!