自己动手打造ajax图片上传

前端之家收集整理的这篇文章主要介绍了自己动手打造ajax图片上传前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天笔者需要一款图片上传插件,但是网上没有提供一款符合自己需求且好用的。于是就自己动手写了一个。

方法1,仅使用jquery代码,不用第三方插件代码如下

  1. <p>
  2. <label>上传图片</label>
  3. <input class="ke-input-text" type="text" id="url" value="" readonly="readonly" />
  4. <input type="button" id="uploadButton" value="Upload" />
  5. </p>
  6. <script type="text/javascript">
  7. $(function() {
  8. $('.inp_fileToUpload').change(function() {
  9. var formdata = new FormData();
  10. var v_this = $(this);
  11. var fileObj = v_this.get(0).files;
  12. url = "/upload/upload_json.ashx";
  13. //var fileObj=document.getElementById("fileToUpload").files;
  14. formdata.append("imgFile",fileObj[0]);
  15. jQuery.ajax({
  16. url : url,type : 'post',data : formdata,cache : false,contentType : false,processData : false,dataType : "json",success : function(data) {
  17. if (data.error == 0) {
  18. v_this.parent().children(".img_upload").attr("src",data.url);
  19. //$("#img").attr("src",data.url);
  20. }
  21. }
  22. });
  23. return false;
  24. });
  25. });
  26. </script>

这种方法的缺点:由于IE6\8\9\不支持formdata,所以这种方法不支持IE9及以下版本

方法二:使用ajaxfileupload.js插件
  1. <p>
  2. <label>ajax上传</label>
  3. <input type="file" name="fileToUpload" id="fileToUpload" class="inp_fileToUpload" multiple="multiple"/>
  4. <img src="$web.site$web.tpl#**#adminht/images/lb_head.jpg" width="30px" height="30px" class="img_upload" id="img" />
  5. </p>
  6. <p>
  7. <label>最新修改人员:</label>
  8. <input readonly="readonly" type="text" size="30" />
  9. </p>
  10. <div>
  11. <script type="text/javascript">
  12. $(function() {
  13. $(".inp_fileToUpload").live("change",function() {//现在这个已经适用于多个file表单。
  14. ajaxFileUpload($(this).attr("id"),$(this).parent().children(".img_upload").attr("id"));
  15. })
  16. })
  17. function ajaxFileUpload(file_id,img_id) {
  18. jQuery.ajaxFileUpload({
  19. url : '/upload/upload_json.ashx',//用于文件上传的服务器端请求地址
  20. secureuri : false,//是否需要安全协议,一般设置为false
  21. fileElementId : file_id,//文件上传域的ID
  22. dataType : 'json',//返回值类型 一般设置为json
  23. success : function(data,status)//服务器成功响应处理函数
  24. {
  25. if (data.error == 0) {
  26. $("#" + img_id).attr("src",data.url);
  27. } else {
  28. alert(data.message);
  29. }
  30. },error : function(data,status,e)//服务器响应失败处理函数
  31. {
  32. alert(e);
  33. }
  34. })
  35. return false;
  36. }
  37. </script>
  38. </div>
  39. </div>


说明:这种方法目前测试支持IE8/9,谷歌,兼容比方法1好。建议采用方法2

文件上传后台处理代码(asp.net版)
  1. <%@ webhandler Language="C#" class="Upload" %>
  2.  
  3. using System;
  4. using System.Collections;
  5. using System.Web;
  6. using System.IO;
  7. using System.Globalization;
  8. using LitJson;
  9. public class Upload : IHttpHandler
  10. {
  11. private HttpContext context;
  12. public void ProcessRequest(HttpContext context)
  13. {
  14. String aspxUrl = context.Request.Path.Substring(0,context.Request.Path.LastIndexOf("/") + 1);
  15. //文件保存目录路径
  16. String savePath = "attached/";
  17. //文件保存目录URL
  18. String saveUrl = aspxUrl + "attached/";
  19. //定义允许上传文件扩展名
  20. Hashtable extTable = new Hashtable();
  21. extTable.Add("image","gif,jpg,jpeg,png,bmp");
  22. extTable.Add("flash","swf,flv");
  23. extTable.Add("media",flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
  24. extTable.Add("file","doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
  25. //最大文件大小
  26. int maxSize = 1000000;
  27. this.context = context;
  28. HttpPostedFile imgFile = context.Request.Files["imgFile"];
  29. if (imgFile == null)
  30. {
  31. showError("请选择文件。");
  32. }
  33. String dirPath = context.Server.MapPath(savePath);
  34. if (!Directory.Exists(dirPath))
  35. {
  36. showError("上传目录不存在。");
  37. }
  38. String dirName = context.Request.QueryString["dir"];
  39. if (String.IsNullOrEmpty(dirName)) {
  40. dirName = "image";
  41. }
  42. if (!extTable.ContainsKey(dirName)) {
  43. showError("目录名不正确。");
  44. }
  45. String fileName = imgFile.FileName;
  46. String fileExt = Path.GetExtension(fileName).ToLower();
  47. if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
  48. {
  49. showError("上传文件大小超过限制。");
  50. }
  51. if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','),fileExt.Substring(1).ToLower()) == -1)
  52. {
  53. showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
  54. }
  55. //创建文件
  56. dirPath += dirName + "/";
  57. saveUrl += dirName + "/";
  58. if (!Directory.Exists(dirPath)) {
  59. Directory.CreateDirectory(dirPath);
  60. }
  61. String ymd = DateTime.Now.ToString("yyyyMMdd",DateTimeFormatInfo.InvariantInfo);
  62. dirPath += ymd + "/";
  63. saveUrl += ymd + "/";
  64. if (!Directory.Exists(dirPath)) {
  65. Directory.CreateDirectory(dirPath);
  66. }
  67. String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff",DateTimeFormatInfo.InvariantInfo) + fileExt;
  68. String filePath = dirPath + newFileName;
  69. imgFile.SaveAs(filePath);
  70. String fileUrl = saveUrl + newFileName;
  71. Hashtable hash = new Hashtable();
  72. hash["error"] = 0;
  73. hash["url"] = fileUrl;
  74. context.Response.AddHeader("Content-Type","text/html; charset=UTF-8");
  75. context.Response.Write(JsonMapper.ToJson(hash));
  76. context.Response.End();
  77. }
  78. private void showError(string message)
  79. {
  80. Hashtable hash = new Hashtable();
  81. hash["error"] = 1;
  82. hash["message"] = message;
  83. context.Response.AddHeader("Content-Type","text/html; charset=UTF-8");
  84. context.Response.Write(JsonMapper.ToJson(hash));
  85. context.Response.End();
  86. }
  87. public bool IsReusable
  88. {
  89. get
  90. {
  91. return true;
  92. }
  93. }
  94. }

猜你在找的Ajax相关文章