本日笔者需要一款图片上传插件,可是网上没有提供一款切合本身需求且好用的。于是就本身动手写了一个。
要领1,仅利用jquery代码,不消第三方插件。代码如下
<p> <label>上传图片</label> <input type="text" value="" readonly="readonly" /> <input type="button" value="Upload" /> </p> <script type="text/javascript"> $(function() { $('.inp_fileToUpload').change(function() { var formdata = new FormData(); var v_this = $(this); var fileObj = v_this.get(0).files; url = "/upload/upload_json.ashx"; //var fileObj=document.getElementById("fileToUpload").files; formdata.append("imgFile", fileObj[0]); jQuery.ajax({ url : url, type : 'post', data : formdata, cache : false, contentType : false, processData : false, dataType : "json", success : function(data) { if (data.error == 0) { v_this.parent().children(".img_upload").attr("src", data.url); //$("#img").attr("src",data.url); } } }); return false; }); }); </script>
这种要领的缺点:由于IE6\8\9\不支持formdata,所以这种要领不支持IE9及以下版本
要领二:利用ajaxfileupload.js插件
ajaxfileupload.js
html代码:
<p> <label>ajax上传</label> <input type="file" multiple="multiple"/> <img src="$web.site$web.tpl#**#adminht/images/lb_head.jpg" /> </p> <p> <label>最新修改人员:</label> <input readonly="readonly" type="text" size="30" /> </p> <div> <script type="text/javascript"> $(function() { $(".inp_fileToUpload").live("change", function() {//此刻这个已经合用于多个file表单。 ajaxFileUpload($(this).attr("id"), $(this).parent().children(".img_upload").attr("id")); }) }) function ajaxFileUpload(file_id, img_id) { jQuery.ajaxFileUpload({ url : '/upload/upload_json.ashx', //用于文件上传的处事器端请求地点 secureuri : false, //是否需要安详协议,一般配置为false fileElementId : file_id, //文件上传域的ID dataType : 'json', //返回值范例 一般配置为json success : function(data, status)//处事器乐成响应处理惩罚函数 { if (data.error == 0) { $("#" + img_id).attr("src", data.url); } else { alert(data.message); } }, error : function(data, status, e)//处事器响应失败处理惩罚函数 { alert(e); } }) return false; } </script> </div> </div>
说明:这种要领今朝测试支持IE8/9,谷歌,兼容比要领1好。发起回收要领2
文件上传靠山处理惩罚代码(asp.net版)
<%@ webhandler Language="C#" %> using System; using System.Collections; using System.Web; using System.IO; using System.Globalization; using LitJson; public class Upload : IHttpHandler { private HttpContext context; public void ProcessRequest(HttpContext context) { String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("https://www.jb51.net/") + 1); //文件生存目次路径 String savePath = "attached/"; //文件生存目次URL String saveUrl = aspxUrl + "attached/"; //界说答允上传的文件扩展名 Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp"); extTable.Add("flash", "swf,flv"); extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); //最大文件巨细 int maxSize = 1000000; this.context = context; HttpPostedFile imgFile = context.Request.Files["imgFile"]; if (imgFile == null) { showError("请选择文件。"); } String dirPath = context.Server.MapPath(savePath); if (!Directory.Exists(dirPath)) { showError("上传目次不存在。"); } String dirName = context.Request.QueryString["dir"]; if (String.IsNullOrEmpty(dirName)) { dirName = "image"; } if (!extTable.ContainsKey(dirName)) { showError("目次名不正确。"); } String fileName = imgFile.FileName; String fileExt = Path.GetExtension(fileName).ToLower(); if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) { showError("上传文件巨细高出限制。"); } if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) { showError("上传文件扩展名是不答允的扩展名。\n只答允" + ((String)extTable[dirName]) + "名目。"); } //建设文件夹 dirPath += dirName + "https://www.jb51.net/"; saveUrl += dirName + "https://www.jb51.net/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); dirPath += ymd + "https://www.jb51.net/"; saveUrl += ymd + "https://www.jb51.net/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; String filePath = dirPath + newFileName; imgFile.SaveAs(filePath); String fileUrl = saveUrl + newFileName; Hashtable hash = new Hashtable(); hash["error"] = 0; hash["url"] = fileUrl; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(JsonMapper.ToJson(hash)); context.Response.End(); } private void showError(string message) { Hashtable hash = new Hashtable(); hash["error"] = 1; hash["message"] = message; context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8"); context.Response.Write(JsonMapper.ToJson(hash)); context.Response.End(); } public bool IsReusable { get { return true; } } }
您大概感乐趣的文章: