jQuery+PHP實(shí)現(xiàn)圖片上傳并提交功能
圖片上傳思路:通過ajax實(shí)現(xiàn)圖片上傳,然后把PHP返回的圖片地址,加入到隱藏字段中,最后通過表單提交給后臺PHP,代碼如下
HTML代碼 zimg.html文件:
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>自定義上傳圖片</title></head><body> <form action='a.php?action=2' method='post'> <span> 上傳圖片 </span> <span> <input type='file' name='img_url' accept='.jpg, .gif, .jpeg, .bmp, .png'/> <a onclick='UpLoadImg()'>上傳</a> <input type='hidden' name='url_data'/> </span> <br> <span> <input type='submit' value='提交'> </span> </form> </body><!-- 引入jq --><script src='https://code.jquery.com/jquery-3.0.0.min.js'></script><script> function UpLoadImg(){ //獲取上傳文件 var formData = new FormData(); formData.append(’img_url’, $(’#img_url’)[0].files[0]); console.log(formData) //提交后臺處理 $.ajax({ url: ’a.php?action=1’, type: ’POST’, cache: false, data: formData, dataType: 'JSON', processData: false, contentType: false }).done(function(res) { console.log(res.url); if(res.status == 1){ //賦值給字段 $(’#url_data’).val(res.url); alert(res.msg) }else{ alert(res.msg) } }).fail(function(res) { }); }</script></html>
后臺PHP代碼 a.php:
<?phpif($_GET[’action’] == 1){//上傳圖片接口 $img = $_FILES[’img_url’]; //獲取上圖片后綴 $type = strstr($img[’name’], ’.’); $rand = rand(1000, 9999); //命名圖片名稱 $pics = date('YmdHis') . $rand . $type; //上傳路徑 $pic_path = 'img/'. $pics; //移動到指定目錄,上傳圖片 $res = move_uploaded_file($img[’tmp_name’], $pic_path); if($res){ echo json_encode([’status’ => 1, ’msg’ => ’上傳成功’,’url’ => $pic_path]);exit; }else{ echo json_encode([’status’ => 0, ’msg’ => ’上傳失敗’]);exit; }}elseif($_GET[’action’] == 2){//提交文件表單 echo ’<pre>’; var_dump($_POST);}
最后實(shí)現(xiàn)效果如下:
ps:js代碼是使用jQuery的寫法,需引入jQuery代碼庫文件
到此這篇關(guān)于jQuery加PHP實(shí)現(xiàn)圖片上傳并提交實(shí)現(xiàn)詳解的文章就介紹到這了,更多相關(guān)jQuery加PHP實(shí)現(xiàn)圖片上傳并提交內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 部署vue+Springboot前后端分離項(xiàng)目的步驟實(shí)現(xiàn)2. html清除浮動的6種方法示例3. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解4. Python基于Serializer實(shí)現(xiàn)字段驗(yàn)證及序列化5. idea設(shè)置自動導(dǎo)入依賴的方法步驟6. PHP字符串前后字符或空格刪除方法介紹7. 網(wǎng)頁中img圖片使用css實(shí)現(xiàn)等比例自動縮放不變形(代碼已測試)8. Python安裝并操作redis實(shí)現(xiàn)流程詳解9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺】
