当前位置:Gxlcms > AJAX > 自己动手打造ajax图片上传(网上没有的)

自己动手打造ajax图片上传(网上没有的)

时间:2021-07-01 10:21:17 帮助过:42人阅读

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

方法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,
  17. type : 'post',
  18. data : formdata,
  19. cache : false,
  20. contentType : false,
  21. processData : false,
  22. dataType : "json",
  23. success : function(data) {
  24. if (data.error == 0) {
  25. v_this.parent().children(".img_upload").attr("src", data.url);
  26. //$("#img").attr("src",data.url);
  27. }
  28. }
  29. });
  30. return false;
  31. });
  32. });
  33. </script>

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

方法二:使用ajaxfileupload.js插件
ajaxfileupload.js
html代码:

  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. },
  31. error : function(data, status, e)//服务器响应失败处理函数
  32. {
  33. alert(e);
  34. }
  35. })
  36. return false;
  37. }
  38. </script>
  39. </div>
  40. </div>


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

文件上传后台处理代码(asp.net版)

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

人气教程排行