jQuery AjaxUpload 上傳圖片代碼,

來源:互聯網
上載者:User

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',檔案上傳伺服器端執行的地址action: '/handler/AjaxuploadHandler.ashx',name: 'myfile',onSubmit: function (file, ext) {if (!(ext && /^(jpg|jpeg|JPG|JPEG)$/.test(ext))) {alert('圖片格式不正確,請選擇 jpg 格式的檔案!', '系統提示');return false;}// change button text, when user selects filebutton.text('上傳中');// If you want to allow uploading only 1 file at time,// you can disable upload buttonthis.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 伺服器端傳回的資訊button.text('上傳圖片(只允許上傳JPG格式的圖片,大小不得大於150K)');window.clearInterval(interval);// enable upload buttonthis.enable();var k = response.replace("<PRE>", "").replace("</PRE>", "");if (k == '-1') {alert('您上傳的檔案太大啦!請不要超過150K');}else {alert("伺服器端傳回的串:"+k);alert("本地檔案名稱:"+file);$("#txtFileName").val(k);$("<img />").appendTo($('#imglist')).attr("src", k);}}});});</script> 

伺服器端 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; //150Kstring 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);elseimg.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網站開發中,檔案上傳功能時常用到,之前我已介紹過如何利用PHP實現檔案上傳功能。隨著WEB技術的發展,使用者體驗成為衡量網站成功與否的關鍵,今天和大家分享如何在PHP中利用Jquery實現Ajax方式檔案上傳功能的例子,其中使用到了Jquery外掛程式Ajaxupload,其可以實現單個檔案和多檔案上傳功能。

AjaxUpload

  Jquery外掛程式AjaxUpload實現檔案上傳功能時無需建立form表單,即可實現Ajax方式的檔案上傳,當然根據需要也可以建立form表單。

準備工作

1、下載Jquery開發包和檔案上傳外掛程式AjaxUpload。

2、建立uploadfile.html,並引入Jquery開發包和AjaxUpload外掛程式

<script src="js/jquery-1.3.js"></script><script src="js/ajaxupload.3.5.js"></script> 

3、根據Jquery外掛程式AjaxUpload的需要,建立一個觸發Ajax檔案上傳功能的DIV

<ul> <li id="example"> <div id="upload_button">檔案上傳</div><p>已上傳的檔案清單:</p> <ol class="files"></ol></ul> 

注釋:由下面的代碼我們可以看到Jquery外掛程式AjaxUpload是根據upload_button這個DIV觸發檔案上傳功能。

前台JS代碼

  在代碼中我設定了開關,根據需要可以匹配上傳檔案類型,同時也可以設定是以Ajax方式實現單個檔案上傳還是多個檔案上傳。

$(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()函數,Jquery中的函數,類似於window.load,使用這個函數可在DOM載入就緒能夠讀取並操縱時立即調用綁定的函數。

第3行:fileType和fileNum參數代表上傳檔案的類型和數量,預設值為可上傳所有類型檔案,同一時間只能上傳一個檔案,如想上傳圖片檔案或同時上傳多個檔案,可將這兩個變數值變為pic和more。

第6~8行:POST到伺服器的資料,你可以設定靜態值也可以通過Jquery的DOM操作函數獲得一些動態值,比如form表單中INPUT的值等。

第9行:等同於前端

<input type="file" name="userfile"> 

伺服器端$_FILES['userfile']

第10~36行:檔案上傳前觸發的功能。

第11~21行:圖片檔案類型的過濾功能,Jquery setData函數用來設定POST至伺服器端的值。

第25~26行:設定同時只上傳一個檔案還是多個檔案,如果只上傳一個檔案,則將觸發按鈕禁掉。如果要多傳輸幾個檔案,請在伺服器端PHP檔案上傳程式中設定MAXSIZE的值,當然上傳檔案的大小限制同時和PHP.INI檔案中的設定也有關。

第28~35行:在檔案上傳過程中每隔200毫秒動態更新一次按鈕的文字,已實現動態提示的效果。window.setInterval函數用來每隔指定的時間就執行一次內建的函數,互動時間單位為豪秒。

第37~49行:檔案上傳功能完成後觸發的功能,根據傳回值如果伺服器端報錯,則前端通過ALERT方式提示出錯資訊。

伺服器端PHP檔案上傳代碼

  大體上是根據之前介紹的PHP檔案上傳功能代碼執行個體教程改編,涉及到的檔案上傳大小的設定,出錯資訊等說明都已在此文中詳細說明。

$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 "檔案上傳目錄不存在並且無法建立檔案上傳目錄";if(!chmod($upload_dir,0755))echo "檔案上傳目錄的許可權無法設定為可讀可寫";}if($_FILES['userfile']['size']>$MAX_SIZE)echo "上傳的檔案大小超過了規定大小";if($_FILES['userfile']['size'] == 0)echo "請選擇上傳的檔案";if(!move_uploaded_file( $_FILES['userfile']['tmp_name'], $file_path))echo "複製檔案失敗,請重新上傳"; 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;}

總結

  基本上前端Ajax檔案上傳觸發功能和伺服器端PHP檔案上傳功能的原型就介紹完畢了,你可以根據自身需要對前後端代碼進行補充,也可以將一些功能獨立出來,比如檔案類型、單個檔案或者多檔案上傳功能。總的來說Jquery外掛程式AjaxUpload實現檔案上傳功能的應用還是比較容易的。

您可能感興趣的文章:
  • jquery外掛程式ajaxupload實現檔案上傳操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.