jQuery+ThinkPHP實現圖片上傳
阿新 • • 發佈:2020-07-24
本文例項為大家分享了jQuery+ThinkPHP實現圖片上傳的具體程式碼,供大家參考,具體內容如下
一,利用js實現上傳圖片時,實時預覽相關程式碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>預覽選擇的圖片</title> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> </head> <body> <input type="file" onchange="showSelectedImages(this.files)" id="uploadInput"> <br/> <div id="fileList"></div> </body> <script> window.URL = window.URL || window.webkitURL; /** * 顯示選擇的檔案預覽 * @param {[type]} files 選擇的檔案 */ function showSelectedImages(files) { var fileList = document.getElementById('fileList'); if (isImageByType(files[0].type)) { var img = '<img src="' + window.URL.createObjectURL(files[0]) + '" style="width:200px;">'; $('#fileList').html(img); }else{ alert('請選擇圖片'); } } /** * 判斷檔案是否是圖片 * @param {[type]} fileType 檔案 * @return {Boolean} */ function isImageByType(fileType) { return fileType.indexOf("image") < 0 ? false : true; } </script> </html>
二、利用jQuery的Ajax上傳圖片表單
var formData = new FormData(); formData.append('file',$('#uploadimg')[0].files[0]); //新增圖片資訊的引數 formData.append("ewmclass",ewmclass); formData.append("uname",uname); formData.append("skaccount",skaccount); $.ajax({ url: "/User/ewmup",type: "post",dataType: "json",cache: false,data: formData,processData: false,// 不處理資料 contentType: false,// 不設定內容型別 success: function (mes) { if(mes.status == 1){ msg_alert(mes.message,mes.url); }else{ msg_alert(mes.message); } } });
三、ThinkPHP上傳檔案相關程式碼
//圖片上傳 $upload = new \Think\Upload();// 例項化上傳類 $upload->maxSize = 3145728 ;// 設定附件上傳大小 $upload->exts = array('jpg','jpeg','png','gif');// 設定附件上傳型別 $upload->rootPath = './Uploads/'; // 設定附件上傳根目錄 $upload->savePath = 'ewm_img/'; // 設定附件上傳(子)目錄 // 上傳檔案 $info = $upload->upload(); if(!$info) {// 上傳錯誤提示錯誤資訊 echo $upload->getError() exit; } echo '檔案上傳目錄為:/Uploads/'.$info['file']['savepath'].$info['file']['savename'];
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。