jQuery AjaxUpload 上傳圖片代碼
本次使用AJAXUPLOAD做為上傳客戶端無刷上傳插件,其最新版本為3.9,官方地址:http://valums.com/ajax-upload/
在頁面中引入 jquery.min.1.4.2.js 和 ajaxupload.js
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="Scripts/ajaxupload3.9.js" type="text/javascript"></script>
HTML 代碼:
<style type="text/css"> #txtFileName { width: 300px; } .btnsubmit{border-bottom: #cc4f00 1px solid; border-left: #ff9000 1px solid;border-top: #ff9000 1px solid; border-right: #cc4f00 1px solid;text-align: center; padding: 2px 10px; line-height: 16px; background: #e36b0f; height: 24px; color: #fff; font-size: 12px; cursor: pointer;} </style> 上傳圖片:<input type="text" id="txtFileName" /><div id="btnUp" style="width:300px;" class=btnsubmit >瀏覽</div> <div id="imglist"></div>
js代 碼:
<script type="text/javascript"> $(function () { var button = $('#btnUp'), interval; new AjaxUpload(button, { //action: 'upload-test.php',文件上傳服務(wù)器端執(zhí)行的地址 action: '/handler/AjaxuploadHandler.ashx', name: 'myfile', onSubmit: function (file, ext) { if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) { alert('圖片格式不正確,請選擇 jpg 格式的文件!', '系統(tǒng)提示'); return false; } // change button text, when user selects file button.text('上傳中'); // If you want to allow uploading only 1 file at time, // you can disable upload button this.disable(); // Uploding -> Uploading. -> Uploading... interval = window.setInterval(function () { var text = button.text(); if (text.length < 10) { button.text(text + '|'); } else { button.text('上傳中'); } }, 200); }, onComplete: function (file, response) { //file 本地文件名稱,response 服務(wù)器端傳回的信息 button.text('上傳圖片(只允許上傳JPG格式的圖片,大小不得大于150K)'); window.clearInterval(interval); // enable upload button this.enable(); var k = response.replace("<PRE>", "").replace("</PRE>", ""); if (k == '-1') { alert('您上傳的文件太大啦!請不要超過150K'); } else { alert("服務(wù)器端傳回的串:"+k); alert("本地文件名稱:"+file); $("#txtFileName").val(k); $("<img />").appendTo($('#imglist')).attr("src", k); } } }); }); </script>
服務(wù)器端 ajaxuploadhandler.ashx 代碼
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile postedFile = context.Request.Files[0]; string savePath = "/upload/images/"; int filelength = postedFile.ContentLength; int fileSize = 163600; //150K string fileName = "-1"; //返回的上傳后的文件名 if (filelength <= fileSize) { byte[] buffer = new byte[filelength]; postedFile.InputStream.Read(buffer, 0, filelength); fileName = UploadImage(buffer, savePath, "jpg"); } context.Response.Write(fileName); } public static string UploadImage(byte[] imgBuffer, string uploadpath, string ext) { try { System.IO.MemoryStream m = new MemoryStream(imgBuffer); if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadpath))) Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadpath)); string imgname = CreateIDCode() + "." + ext; string _path = HttpContext.Current.Server.MapPath(uploadpath) + imgname; Image img = Image.FromStream(m); if (ext == "jpg") img.Save(_path, System.Drawing.Imaging.ImageFormat.Jpeg); else img.Save(_path, System.Drawing.Imaging.ImageFormat.Gif); m.Close(); return uploadpath + imgname; } catch (Exception ex) { return ex.Message; } } public static string CreateIDCode() { DateTime Time1 = DateTime.Now.ToUniversalTime(); DateTime Time2 = Convert.ToDateTime("1970-01-01"); TimeSpan span = Time1 - Time2; //span就是兩個日期之間的差額 string t = span.TotalMilliseconds.ToString("0"); return t; }
在PHP網(wǎng)站開發(fā)中,文件上傳功能時常用到,之前我已介紹過如何利用PHP實現(xiàn)文件上傳功能。隨著WEB技術(shù)的發(fā)展,用戶體驗成為衡量網(wǎng)站成功與否的關(guān)鍵,今天和大家分享如何在PHP中利用Jquery實現(xiàn)Ajax方式文件上傳功能的例子,其中使用到了Jquery插件Ajaxupload,其可以實現(xiàn)單個文件和多文件上傳功能。
AjaxUpload
Jquery插件AjaxUpload實現(xiàn)文件上傳功能時無需創(chuàng)建form表單,即可實現(xiàn)Ajax方式的文件上傳,當(dāng)然根據(jù)需要也可以創(chuàng)建form表單。
準(zhǔn)備工作
1、下載Jquery開發(fā)包和文件上傳插件AjaxUpload。
2、創(chuàng)建uploadfile.html,并引入Jquery開發(fā)包和AjaxUpload插件
<script src="js/jquery-1.3.js"></script> <script src="js/ajaxupload.3.5.js"></script>
3、根據(jù)Jquery插件AjaxUpload的需要,創(chuàng)建一個觸發(fā)Ajax文件上傳功能的DIV
<ul> <li id="example"> <div id="upload_button">文件上傳</div> <p>已上傳的文件列表:</p> <ol class="files"></ol> </ul>
注釋:由下面的代碼我們可以看到Jquery插件AjaxUpload是根據(jù)upload_button這個DIV觸發(fā)文件上傳功能。
前臺JS代碼
在代碼中我設(shè)置了開關(guān),根據(jù)需要可以匹配上傳文件類型,同時也可以設(shè)置是以Ajax方式實現(xiàn)單個文件上傳還是多個文件上傳。
$(document).ready(function(){ var button = $('#upload_button'), interval; var fileType = "all",fileNum = "one"; new AjaxUpload(button,{ action: 'do/uploadfile.php', /*data:{ 'buttoninfo':button.text() },*/ name: 'userfile', onSubmit : function(file, ext){ if(fileType == "pic") { if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){ this.setData({ 'info': '文件類型為圖片' }); } else { $('<li></li>').appendTo('#example .files').text('非圖片類型文件,請重傳'); return false; } } button.text('文件上傳中'); if(fileNum == 'one') this.disable(); interval = window.setInterval(function(){ var text = button.text(); if (text.length < 14){ button.text(text + '.'); } else { button.text('文件上傳中'); } }, 200); }, onComplete: function(file, response){ if(response != "success") alert(response); button.text('文件上傳'); window.clearInterval(interval); this.enable(); if(response == "success"); $('<li></li>').appendTo('#example .files').text(file); } }); });
注釋:
第1行:$(document).ready()函數(shù),Jquery中的函數(shù),類似于window.load,使用這個函數(shù)可在DOM載入就緒能夠讀取并操縱時立即調(diào)用綁定的函數(shù)。
第3行:fileType和fileNum參數(shù)代表上傳文件的類型和數(shù)量,默認(rèn)值為可上傳所有類型文件,同一時間只能上傳一個文件,如想上傳圖片文件或同時上傳多個文件,可將這兩個變量值變?yōu)閜ic和more。
第6~8行:POST到服務(wù)器的數(shù)據(jù),你可以設(shè)置靜態(tài)值也可以通過Jquery的DOM操作函數(shù)獲得一些動態(tài)值,比如form表單中INPUT的值等。
第9行:等同于前端
<input type="file" name="userfile">
服務(wù)器端$_FILES['userfile']
第10~36行:文件上傳前觸發(fā)的功能。
第11~21行:圖片文件類型的過濾功能,Jquery setData函數(shù)用來設(shè)置POST至服務(wù)器端的值。
第25~26行:設(shè)置同時只上傳一個文件還是多個文件,如果只上傳一個文件,則將觸發(fā)按鈕禁掉。如果要多傳輸幾個文件,請在服務(wù)器端PHP文件上傳程序中設(shè)置MAXSIZE的值,當(dāng)然上傳文件的大小限制同時和PHP.INI文件中的設(shè)置也有關(guān)。
第28~35行:在文件上傳過程中每隔200毫秒動態(tài)更新一次按鈕的文字,已實現(xiàn)動態(tài)提示的效果。window.setInterval函數(shù)用來每隔指定的時間就執(zhí)行一次內(nèi)置的函數(shù),交互時間單位為豪秒。
第37~49行:文件上傳功能完成后觸發(fā)的功能,根據(jù)返回值如果服務(wù)器端報錯,則前端通過ALERT方式提示出錯信息。
服務(wù)器端PHP文件上傳代碼
大體上是根據(jù)之前介紹的PHP文件上傳功能代碼實例教程改編,涉及到的文件上傳大小的設(shè)置,出錯信息等說明都已在此文中詳細(xì)說明。
$upload_dir = '../file/'; $file_path = $upload_dir . $_FILES['userfile']['name']; $MAX_SIZE = 20000000; echo $_POST['buttoninfo']; if(!is_dir($upload_dir)) { if(!mkdir($upload_dir)) echo "文件上傳目錄不存在并且無法創(chuàng)建文件上傳目錄"; if(!chmod($upload_dir,0755)) echo "文件上傳目錄的權(quán)限無法設(shè)定為可讀可寫"; } if($_FILES['userfile']['size']>$MAX_SIZE) echo "上傳的文件大小超過了規(guī)定大小"; if($_FILES['userfile']['size'] == 0) echo "請選擇上傳的文件"; if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path)) echo "復(fù)制文件失敗,請重新上傳"; switch($_FILES['userfile']['error']) { case 0: echo "success" ; break; case 1: echo "上傳的文件超過了 php.ini 中 upload_max_filesize 選項限制的值"; break; case 2: echo "上傳文件的大小超過了 HTML 表單中 MAX_FILE_SIZE 選項指定的值"; break; case 3: echo "文件只有部分被上傳"; break; case 4: echo "沒有文件被上傳"; break; }
總結(jié)
基本上前端Ajax文件上傳觸發(fā)功能和服務(wù)器端PHP文件上傳功能的原型就介紹完畢了,你可以根據(jù)自身需要對前后端代碼進(jìn)行補(bǔ)充,也可以將一些功能獨(dú)立出來,比如文件類型、單個文件或者多文件上傳功能??偟膩碚fJquery插件AjaxUpload實現(xiàn)文件上傳功能的應(yīng)用還是比較容易的。
- Jquery ajaxsubmit上傳圖片實現(xiàn)代碼
- 基于jquery實現(xiàn)的上傳圖片及圖片大小驗證、圖片預(yù)覽效果代碼
- jquery的ajaxSubmit()異步上傳圖片并保存表單數(shù)據(jù)演示代碼
- jquery 批量上傳圖片實現(xiàn)代碼
- 使用jQuery實現(xiàn)驗證上傳圖片的格式與大小
- 簡單實現(xiàn)jQuery上傳圖片顯示預(yù)覽功能
- JQuery+ajax實現(xiàn)批量上傳圖片(自寫)
- jQuery實現(xiàn)上傳圖片前預(yù)覽效果功能
- 基于Jquery插件Uploadify實現(xiàn)實時顯示進(jìn)度條上傳圖片
- jquery實現(xiàn)上傳圖片功能
相關(guān)文章
jquery實現(xiàn)上傳文件大小類型的驗證例子(推薦)
下面小編就為大家?guī)硪黄猨query實現(xiàn)上傳文件大小類型的驗證例子(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨想過來看看吧2016-06-06jquery的trigger和triggerHandler的區(qū)別示例介紹
這篇文章主要介紹了jquery的trigger和triggerHandler的區(qū)別,需要的朋友可以參考下2014-04-04