今天筆者需要一款圖片上傳插件,但是網(wǎng)上沒有提供一款符合自己需求且好用的。于是就自己動(dòng)手寫了一個(gè)。
方法1,僅使用jquery代碼,不用第三方插件。代碼如下
p> label>上傳圖片/label> input class="ke-input-text" type="text" id="url" value="" readonly="readonly" /> input type="button" id="uploadButton" 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>
這種方法的缺點(diǎn):由于IE6\8\9\不支持formdata,所以這種方法不支持IE9及以下版本
方法二:使用ajaxfileupload.js插件
ajaxfileupload.js
html代碼:
p> label>ajax上傳/label> input type="file" name="fileToUpload" id="fileToUpload" class="inp_fileToUpload" multiple="multiple"/> img src="$web.site$web.tpl#**#adminht/images/lb_head.jpg" width="30px" height="30px" class="img_upload" id="img" /> /p> p> label>最新修改人員:/label> input readonly="readonly" type="text" size="30" /> /p> div> script type="text/javascript"> $(function() { $(".inp_fileToUpload").live("change", function() {//現(xiàn)在這個(gè)已經(jīng)適用于多個(gè)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', //用于文件上傳的服務(wù)器端請求地址 secureuri : false, //是否需要安全協(xié)議,一般設(shè)置為false fileElementId : file_id, //文件上傳域的ID dataType : 'json', //返回值類型 一般設(shè)置為json success : function(data, status)//服務(wù)器成功響應(yīng)處理函數(shù) { if (data.error == 0) { $("#" + img_id).attr("src", data.url); } else { alert(data.message); } }, error : function(data, status, e)//服務(wù)器響應(yīng)失敗處理函數(shù) { alert(e); } }) return false; } /script> /div> /div>
說明:這種方法目前測試支持IE8/9,谷歌,兼容比方法1好。建議采用方法2
文件上傳后臺處理代碼(asp.net版)
%@ webhandler Language="C#" class="Upload" %> 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("/") + 1); //文件保存目錄路徑 String savePath = "attached/"; //文件保存目錄URL String saveUrl = aspxUrl + "attached/"; //定義允許上傳的文件擴(kuò)展名 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("上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\n只允許" + ((String)extTable[dirName]) + "格式。"); } //創(chuàng)建文件夾 dirPath += dirName + "/"; saveUrl += dirName + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); dirPath += ymd + "/"; saveUrl += ymd + "/"; 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; } } }
標(biāo)簽:揭陽 股票 荊州 佛山 辛集 咸寧 商洛 紅河
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《自己動(dòng)手打造ajax圖片上傳(網(wǎng)上沒有的)》,本文關(guān)鍵詞 自己,動(dòng)手,打造,ajax,圖片,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。