欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ajax图片上传,图片异步上传,更新实例

程序员文章站 2023-08-28 08:55:52
最近在研究ajax图片上传,图片异步上传,更新,留作参考。 直接上源码吧: js源码: ///

最近在研究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" } } 
 }); 
}); 
 
//上传成功后执行该函数 
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: {},   //上传时需要附加的参数 
 deletedata: {},   //删除时需要附加的参数 
 deletefn: function ($parent, showmessage) { //删除图片的方法(默认方法使用post提交) 
  methods.deleteimage($parent, showmessage); 
 }, 
 beforesubmitfn: "beforeupload",  //上传前执行的方法 原型 beforesubmit(arr, $form, options); 
 successfn: "uploadsuccess",  //上传成功后执行的方法 uploadsuccess(response, statustext, xhr, $this) 
 errorfn: "uploaderror"   //上传失败后执行的方法 
 }, settings); 
 
 //上传准备函数 
 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); 
 }, 
 //创建表单 
 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); //创建表单后一定要加上这句否则得到的form不能上传。document后要加上body,否则火狐下不行。 
  return $($form); 
 }, 
 //创建图片 
 createimage: function () { 
  //不能用 new image() 来创建图片,否则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); 
  } 
 } 
 }; 
 //上传主函数 
 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); 
  } 
 
  //创建表单 
  var $form = methods.createform(); 
 
  //把上传控件附加到表单 
  $fileinput.appendto($form); 
  filebox.html("<img src=\"/admin/styles/images/loading.gif\" /> 正在上传... "); 
  $this.attr("disabled", true); 
 
  //构建ajaxsubmit参数 
  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" } } 
 }); 
 }); 
 
 //上传成功后执行该函数 
 function success(response, statustext, xhr, $this) { 
 //比如插入编辑器 
 alert(response.data.relativepath + $this.attr("value")) 
 } 
</script> 
</body> 
</html> 

服务器端使用一般处理程序:

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, "没有权限或无效请求。").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, "没有可处理的数据。").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, "没有可处理的数据。").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, "发生错误。").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> 
 /// 权限不足 
 /// </summary> 
 noaccess = -2, 
 /// <summary> 
 /// 错误 
 /// </summary> 
 error = -1, 
 /// <summary> 
 /// 成功 
 /// </summary> 
 success = 1, 
 
 /// <summary> 
 /// 提示信息 
 /// </summary> 
 hint = 0 
} 

其他的扩展方法就不一一给出来了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。