1. 程式人生 > 實用技巧 >jQuery加PHP實現圖片上傳並提交

jQuery加PHP實現圖片上傳並提交

圖片上傳思路:通過ajax實現圖片上傳,然後把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" id="img_url" name="img_url" accept=".jpg, .gif, .jpeg, .bmp, .png"/> <a onclick="UpLoadImg()"
>上傳</a> <input type="hidden" id="url_data" 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:

<?php
if($_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);
}

最後實現效果如下:

ps:js程式碼是使用jQuery的寫法,需引入jQuery程式碼庫檔案