欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ajax圖片上傳,圖片異步上傳,更新實例

 更新時間:2016年12月30日 09:26:57   作者:weizengxun  
本篇文章主要介紹了ajax圖片上傳,圖片異步上傳,更新,具有一定的參考價值,有想去的可以了解一下。

最近在研究ajax圖片上傳,圖片異步上傳,更新,留作參考。

直接上源碼吧:

js源碼:

/// <reference path="jquery-1.8.3.js" /> 
/// <reference path="ajaxForm/jquery.form.js" /> 
 
/*! 
 * jQuery upload 
 * 用于上傳單個文件,上傳成功后,返回文件路徑。 
 * 本插件依賴jQuery,jquery.form 請在使用時引入依賴的文件 
 * 
 * Date: 2014/4/23 
 */ 
/* 
<div style="width: 100%; float: left;"> 
 <input type="hidden" id="hfThumbnail" value="/uploads/2014/04/23/635338686611432716.jpg" /> 
 <div class="imgdiv"></div> 
 <span class="img_span"> 
 <input type="file" name="file" /> 
 </span> 
 
 <input type="button" value="上傳" class="upload" /> 
</div> 
<div style="width: 100%; float: left;"> 
 <input type="hidden" id="hfThumbnail" value="/uploads/2014/04/23/635338686611432716.jpg" /> 
 <div class="imgdiv"></div> 
 <span class="img_span"> 
 <input type="file" name="file" /> 
 </span> 
 <input type="button" value="上傳" class="upload" /> 
</div> 

js: 

$(document).ready(function () { 
 
 //$(".upload").upload({ 
 // uploadData: { id: "12233" }, 
 // successFn: function (response, statusText, xhr, $this) { 
 // alert(response.Data.RelativePath) 
 // }, 
 // deleteData: { id: function () { return "asdfasdf" } } 
 //}); 
 
 $(".upload").upload({ 
 uploadData: { id: "12233" }, 
 successFn: "success", //可以是字符串 
 deleteData: { id: function () { return "asdfasdf" } } 
 }); 
}); 
 
//上傳成功后執(zhí)行該函數(shù) 
function success(response, statusText, xhr, $this) { 
 //比如插入編輯器 
 alert(response.Data.RelativePath + $this.attr("value")) 
} 
*/ 
 
(function ($) { 
 $.extend($.fn, { 
 upload: function (settings) { 
 
 var options = $.extend({ 
 fileType: "gif|jpg|jpeg|png|bmp",  //允許的文件格式 
 uploadUrl: "/ajax/handler.ashx?action=uploadfile", //上傳URL地址 
 deleteUrl: "/ajax/handler.ashx?action=deletefile", //刪除URL地址 
 width: "",   //圖片顯示的寬度 
 height: 100,   //圖片顯示的高度 
 imgSelector: ".imgdiv",   //圖片選擇器 
 uploadData: {},   //上傳時需要附加的參數(shù) 
 deleteData: {},   //刪除時需要附加的參數(shù) 
 deleteFn: function ($parent, showMessage) { //刪除圖片的方法(默認方法使用POST提交) 
  methods.deleteImage($parent, showMessage); 
 }, 
 beforeSubmitFn: "beforeUpload",  //上傳前執(zhí)行的方法 原型 beforeSubmit(arr, $form, options); 
 successFn: "uploadSuccess",  //上傳成功后執(zhí)行的方法 uploadSuccess(response, statusText, xhr, $this) 
 errorFn: "uploadError"   //上傳失敗后執(zhí)行的方法 
 }, settings); 
 
 //上傳準備函數(shù) 
 var methods = { 
 //驗證文件格式 
 checkFile: function (filename) { 
  var pos = filename.lastIndexOf("."); 
  var str = filename.substring(pos, filename.length); 
  var str1 = str.toLowerCase(); 
  if (typeof options.fileType !== 'string') { options.fileType = "gif|jpg|jpeg|png|bmp"; } 
  var re = new RegExp("\.(" + options.fileType + ")$"); 
  return re.test(str1); 
 }, 
 //創(chuàng)建表單 
 createForm: function () { 
  var $form = document.createElement("form"); 
  $form.action = options.uploadUrl; 
  $form.method = "post"; 
  $form.enctype = "multipart/form-data"; 
  $form.style.display = "none"; 
  //將表單加當document上, 
  document.body.appendChild($form); //創(chuàng)建表單后一定要加上這句否則得到的form不能上傳。document后要加上body,否則火狐下不行。 
  return $($form); 
 }, 
 //創(chuàng)建圖片 
 createImage: function () { 
  //不能用 new Image() 來創(chuàng)建圖片,否則ie下不能改變img 的寬高 
  var img = $(document.createElement("img")); 
  img.attr({ "title": "雙擊圖片可刪除圖片!" }); 
  if (options.width !== "") { 
  img.attr({ "width": options.width }); 
  } 
  if (options.height !== "") { 
  img.attr({ "height": options.height }); 
  } 
  return img; 
 }, 
 showImage: function (filePath, $parent) { 
  var $img = methods.createImage(); 
  $parent.find(options.imgSelector).find("img").remove(); 
  //要先append再給img賦值,否則在ie下不能縮小寬度。 
  $img.appendTo($parent.find(options.imgSelector)); 
  $img.attr("src", filePath); 
  this.bindDelete($parent); 
 }, 
 bindDelete: function ($parent) { 
  $parent.find(options.imgSelector).find("img").bind("dblclick", function () { 
  options.deleteFn($parent, true); 
  }); 
 }, 
 deleteImage: function ($parent, showMessage) { 
  var $fileInput = $parent.find("input:hidden"); 
  if ($fileInput.val() !== "") { 
 
  var data = $.extend(options.deleteData, { filePath: $fileInput.val(), t: Math.random() }); 
 
  $.post(options.deleteUrl, data, function (response) { 
 
  if (showMessage) { alert(response.MessageContent) } 
 
  if (response.MessageType == 1) { 
  $fileInput.val(""); 
  $parent.find(options.imgSelector).find("img").remove(); 
  } 
  }, "JSON"); 
  } 
 }, 
 onload: function ($parent) { 
  var hiddenInput = $parent.find("input:hidden"); 
  if (typeof hiddenInput !== "undefined" && hiddenInput.val() !== "") { 
  var img = methods.createImage(); 
  if ($parent.find(options.imgSelector).find("img").length > 0) { $parent.find(options.imgSelector).find("img").remove(); } 
  //要先append再給img賦值,否則在ie下不能縮小寬度。 
  img.appendTo($parent.find(options.imgSelector)); 
  img.attr("src", hiddenInput.val()); 
  methods.bindDelete($parent); 
  } 
 } 
 }; 
 //上傳主函數(shù) 
 this.each(function () { 
 var $this = $(this); 
 methods.onload($this.parent()); 
 $this.bind("click", function () { 
  var $fileInput = $(this).parent().find("input:file"); 
  var fileBox = $fileInput.parent(); 
 
  if ($fileInput.val() === "") { 
  alert("請選擇要上傳的圖片!"); 
  return false; 
  } 
  //驗證圖片 
  if (!methods.checkFile($fileInput.val())) { 
  alert("文件格式不正確,只能上傳格式為:" + options.fileType + "的文件。"); 
  return false; 
  } 
  //若隱藏域中有圖片,先刪除圖片 
  if ($fileInput.val() !== "") { 
  options.deleteFn($this.parent(), false); 
  //methods.deleteImage($this.parent(), false); 
  } 
 
  //創(chuàng)建表單 
  var $form = methods.createForm(); 
 
  //把上傳控件附加到表單 
  $fileInput.appendTo($form); 
  fileBox.html("<img src=\"/admin/styles/images/loading.gif\" /> 正在上傳... "); 
  $this.attr("disabled", true); 
 
  //構(gòu)建ajaxSubmit參數(shù) 
  var data = {}; 
  data.data = options.uploadData; 
  data.type = "POST"; 
  data.dataType = "JSON"; 
  //上傳前 
  data.beforeSubmit = function (arr, $form, options) { 
 
  var beforeSubmitFn; 
  try { beforeSubmitFn = eval(options.beforeSubmitFn) } catch (err) { }; 
  if (beforeSubmitFn) { 
  var $result = beforeSubmitFn(arr, $form, options); 
  if (typeof ($result) == "boolean") 
  return $result; 
  } 
  }; 
  //上傳失敗 
  data.error = function (response, statusText, xhr, $form) { 
  var errorFn; 
  try { errorFn = eval(options.errorFn) } catch (err) { }; 
  if (errorFn) { 
  errorFn(response.responseText, statusText, xhr, $this); 
  } 
  }; 
  //上傳成功 
  data.success = function (response, statusText, xhr, $form) { 
  //response = eval("(" + response + ")"); 
  if (response.MessageType == 1) { 
  methods.showImage(response.Data.RelativePath, $this.parent()); 
  $this.parent().find("input:hidden").val(response.Data.RelativePath); 
 
  var successFn; 
  try { successFn = eval(options.successFn) } catch (err) { }; 
  if (successFn) { 
  $.ajaxSetup({ cache: false });//這個不能少,否則ie下會提示下載 
  successFn(response, statusText, xhr, $this); 
  } 
 
 
  } else { 
  alert(response.MessageContent); 
  } 
  $this.attr("disabled", false); 
  fileBox.html("<input type=\"file\" name=\"file\" />"); 
  $form.remove(); 
  }; 
 
  try { 
  //開始ajax提交表單 
  $form.ajaxSubmit(data); 
  } catch (e) { 
  alert(e.message); 
  } 
 }); 
 }); 
 } 
 }); 
})(jQuery) 

html代碼:

<!DOCTYPE html> 
 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script src="Scripts/jquery/jquery-1.8.3.js"></script> 
<script src="Scripts/jquery/ajaxForm/jquery.form.js"></script> 
<script src="Scripts/jquery/jquery.upload.js"></script> 
<title></title> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div style="width: 100%; float: left;"> 
 <input type="hidden" id="hfThumbnail" value="/uploads/2014/04/23/635338686611432716.jpg" /> 
 <div class="imgdiv"></div> 
 <span class="img_span"> 
 <input type="file" name="file" /> 
 </span> 
 
 <input type="button" value="上傳" class="upload" /> 
</div> 
<div style="width: 100%; float: left;"> 
 <input type="hidden" id="hfThumbnail" value="/uploads/2014/04/23/635338686611432716.jpg" /> 
 <div class="imgdiv"></div> 
 <span class="img_span"> 
 <input type="file" name="file" /> 
 </span> 
 
 <input type="button" value="上傳" class="upload" /> 
</div> 
</form> 
<script type="text/javascript"> 
 $(document).ready(function () { 
 //$(".upload").upload({ 
 // uploadData: { id: "12233" }, 
 // successFn: function (response, statusText, xhr, $this) { 
 // alert(response.Data.RelativePath) 
 // }, 
 // deleteData: { id: function () { return "asdfasdf" } } 
 //}); 
 $(".upload").upload({ 
 uploadData: { id: "12233" }, 
 successFn: "success", 
 deleteData: { id: function () { return "asdfasdf" } } 
 }); 
 }); 
 
 //上傳成功后執(zhí)行該函數(shù) 
 function success(response, statusText, xhr, $this) { 
 //比如插入編輯器 
 alert(response.Data.RelativePath + $this.attr("value")) 
 } 
</script> 
</body> 
</html> 

服務(wù)器端使用一般處理程序:

public void ProcessRequest(HttpContext context) 
{ 
 context.Response.ContentType = "application/json"; 
 var action = context.Request.QueryString.Get<string>("action").ToLower(); 
 var response = new JsonResult(StatusMessageType.Error, "沒有權(quán)限或無效請求。").ToJson(); 
 switch (action) 
 { 
 
 case "uploadfile": 
 if (context.Request.Files.Count > 0) 
 response = UploadFile(context.Request); 
 break; 
 case "deletefile": 
 response = DeleteFile(context.Request.Form); 
 break; 
 default: 
 break; 
 } 
 context.Response.Write(response); 
} 
/// <summary> 
/// 
/// </summary> 
/// <param name="file"></param> 
/// <returns></returns> 
private string UploadFile(HttpRequest request) 
{ 
 if (request.Files.Count == 0) 
 return new JsonResult(StatusMessageType.Error, "沒有可處理的數(shù)據(jù)。").ToJson(); 
 var id = request.Form.Get<string>("id", ""); 
 
 var file = request.Files[0]; 
 if (file == null || file.ContentLength <= 0 || string.IsNullOrEmpty(file.FileName)) 
 return new JsonResult(StatusMessageType.Error, "沒有可處理的數(shù)據(jù)。").ToJson(); 
 
 //IStoreFile storeFile = null; 
 
 string[] datePaths = new string[] { "~/uploads/" }; 
 datePaths = datePaths.Union(DateTime.Now.ToString("yyyy-MM-dd").Split('-')).ToArray(); 
 var relativePath = storeProvider.JoinDirectory(datePaths); 
 
 var dirPath = HttpContext.Current.Server.MapPath(relativePath); 
 
 if (!System.IO.Directory.Exists(dirPath)) 
 System.IO.Directory.CreateDirectory(dirPath); 
 
 var fileName = GenerateFileName(Path.GetExtension(file.FileName)); 
 
 var filePath = Path.Combine(dirPath, fileName); 
 file.SaveAs(filePath); 
 return new JsonResult(StatusMessageType.Success, "上傳成功。", new 
 { 
 RelativePath = WebUtility.ResolveUrl(Path.Combine(relativePath, fileName)), 
 Size = file.ContentLength, 
 Id = id, 
 }).ToJson(); 
} 
 
public string DeleteFile(NameValueCollection form) 
{ 
 var filePath = form.Get<string>("filePath", "").Trim(); 
 if (string.IsNullOrEmpty(filePath)) 
 return new JsonResult(StatusMessageType.Error, "無效提交。").ToJson(); 
 
 try 
 { 
 if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(filePath))) 
 { 
 System.IO.File.Delete(HttpContext.Current.Server.MapPath(filePath)); 
 return new JsonResult(StatusMessageType.Success, "文件刪除成功。").ToJson(); 
 } 
 else 
 { 
 return new JsonResult(StatusMessageType.Success, "找不到該文件。").ToJson(); 
 } 
 } 
 catch (Exception) 
 { 
 return new JsonResult(StatusMessageType.Hint, "發(fā)生錯誤。").ToJson(); 
 } 
} 
 
/// <summary> 
/// 生成隨機文件名 
/// </summary> 
/// <returns></returns> 
private string GenerateFileName(string extension) 
{ 
 return DateTime.Now.Ticks.ToString() + extension; 
} 

程序使用的是framework4.0,所以使用了一些擴展方法。

JsonTesult類代碼:

[Serializable] 
public class JsonResult 
{ 
 private StatusMessageType _messageType; 
 private string _messageContent; 
 
 
 /// <summary> 
 /// 
 /// </summary> 
 /// <param name="messageType"></param> 
 /// <param name="messageContent"></param> 
 /// <param name="data"></param> 
 public JsonResult(StatusMessageType messageType, string messageContent, object data = null) 
 { 
 _messageType = messageType; 
 _messageContent = messageContent; 
 Data = data; 
 } 
 
 public StatusMessageType MessageType 
 { 
 get { return _messageType; } 
 set { _messageType = value; } 
 } 
 
 public string MessageContent 
 { 
 get { return _messageContent; } 
 set { _messageContent = value; } 
 } 
 
 public object Data { get; set; } 
 
 public string ToJson() 
 { 
 JavaScriptSerializer serializer = new JavaScriptSerializer(); 
 var json = serializer.Serialize(this); 
 
 //string p = @"\\/Date(\d+)\\/"; 
 //MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString); 
 //Regex reg = new Regex(p); 
 //json = reg.Replace(json, matchEvaluator); 
 return json; 
 } 
 
 private static string ConvertJsonDateToDateString(Match m) 
 { 
 string result = string.Empty; 
 DateTime dt = new DateTime(1970, 1, 1); 
 dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); 
 dt = dt.ToLocalTime(); 
 result = dt.ToString("d"); 
 return result; 
 } 
} 

StatusMessageType枚舉類:

/// <summary> 
/// 提示消息類別 
/// </summary> 
public enum StatusMessageType 
{ 
 /// <summary> 
 /// 權(quán)限不足 
 /// </summary> 
 NoAccess = -2, 
 /// <summary> 
 /// 錯誤 
 /// </summary> 
 Error = -1, 
 /// <summary> 
 /// 成功 
 /// </summary> 
 Success = 1, 
 
 /// <summary> 
 /// 提示信息 
 /// </summary> 
 Hint = 0 
} 

其他的擴展方法就不一一給出來了。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論