1. 程式人生 > >TP框架配合jquery進行3種方式的多圖片上傳

TP框架配合jquery進行3種方式的多圖片上傳

用的TP5.1框架+jquery

一 使用form表單方式進行多圖片上傳

html程式碼:

 <form action="../admin/admin/cs" enctype="multipart/form-data" method="post">
       <input type="file" name="image[]" /> <br>
       <input type="file" name="image[]" /> <br>
       <input type="file" name="image[]" /> <br>
       <input type="button" value="上傳" id="imgbtn"/>
</form>

  ../admin/admin/cs的PHP程式碼:


public function cs()
{
// 獲取表單上傳檔案
$files = request()->file('image');

$file_path = ENV::get('root_path') . 'public/ab';

!file_exists($file_path) && mkdir($file_path, 0755, true);

foreach($files as $file){

//move後面加個'',代表使用圖片原檔名,不用則生成隨即檔名可
$info = $file->move($file_path, '');

if(!$info) echo $file->getError();
}
}


 

 

二 使用file的多檔案上傳屬性進行多圖片上傳

html程式碼:

<input type="file" accept="image/*" multiple="multiple" onchange="upload(this)"/>

 jquery程式碼:

let fd = new FormData();

function upload(_this) {

    let filelist = _this.files;

    let l = filelist.length;
  
  //迴圈將檔案全部追加到fd中
    for(i = 0; i < l; i++) fd.append("image[]", filelist[i]);

    $.ajax({
        type: "POST",
        url: "../admin/admin/cs", //這個PHP程式碼還是上面那個
        data: fd,
        processData : false,
        contentType : false,
        success: function(res){
            console.log(res);
        }
    });
}

  

我選了3個檔案,分別是03.jpg     04.jpg      05.jpg

 

 

 

選好之後顯示3個檔案,資料夾中也成功添加了3個對應的檔案,我幫你們看了下,確實是剛才選擇的那3張圖片

 

 

 

三 利用多個file型別input進行ajax無重新整理上傳

html程式碼:

<input type="file" accept="image/*"  onchange="upload(this)"/>
<input type="file" accept="image/*"  onchange="upload(this)"/>
<input type="file" accept="image/*"  onchange="upload(this)"/>
<input type="button" id="btn" value="上傳">

query程式碼:

    let fd = new FormData();

    function upload(_this) {
     //上面是多個檔案,這裡是一個檔案,所以在files後面加個[0]
        fd.append("image[]", _this.files[0])
    };

    $('#btn').click(() =>{
        $.ajax({
            type: "POST",
            url: "../admin/admin/cs", //還是之前那個PHP程式碼
            data: fd,
            processData : false,
            contentType : false,
            success: function(res){

                console.log(res);
            }
        });
    })

  

 

 

 

四 這是我在平時專案開發中使用過的,現在進行一個總結,希望能幫到各位

&n