備忘錄_20160105(定位) 修改 回首頁

程式 2026-06-05 16:46:39 1780649199 100
javascript fetch + php + json + multi-files

javascript fetch + php + json + multi-files


01_fill.php


<!doctype html>
<html lang="zh-Hant-TW">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>上傳資料與多檔</title>
  </head>
  <body>
    <div>
      <div>備註<input type="text" id="inpNote"></div>
      <div>檔案<input type="file" id="inpFiles" multiple></div>
      <div><button type="button" onclick="uploadData();">上傳</button></div>
      <div id="divResult"></div>
    </div>
    <script>
async function uploadData()
{
  let oBtn=event.target;
  oBtn.setAttribute("disabled", "true");
  
  while(true)
  {
    let strNote=document.getElementById("inpNote").value;
    let oFiles=document.getElementById("inpFiles");
    
    let oFormData=new FormData();
    oFormData.append("strJson", JSON.stringify({ "strNote": strNote }));
    for(let i=0; i<oFiles.files.length; i++)
    {
      oFormData.append("oaFile[]", oFiles.files[i]);
    }
    
    try
    {
      var oResponse=await fetch("upload.php", { method: "POST", body: oFormData });
      
      var strJson=await oResponse.text();
      var oJson=JSON.parse(strJson);
      
      document.getElementById("divResult").textContent=strJson;
    }
    catch(oError)
    {
      console.log({ "oResponse":oResponse, "strJson":strJson, "oError":oError });
      alert((oResponse.url+"\n"+oResponse.status+"\n"+oResponse.statusText)+"\n\n"+strJson+"\r\n"+(oError.toString()));
      break;
    }
    
    break;
  }
  
  oBtn.removeAttribute("disabled");
}
    </script>
  </body>
</html>

02_upload.php


<?php
  
  header("Content-Type: application/json; charset=utf-8");
  
  // 資料部份
  $oJson=json_decode($_POST['strJson']);
  
  // 檔案部份
  $iFileCount=count($_FILES['oaFile']['name']);
  for($i=0; $i<$iFileCount; $i++)
  {
    $strSrcFilePath=$_FILES['oaFile']['tmp_name'][$i];
    $strSrcFileName=basename($_FILES['oaFile']['name'][$i]);
    $strDstFilePath="uploadfiles/" . $strSrcFileName;
    
    move_uploaded_file($strSrcFilePath, $strDstFilePath);
  }
  
  // 回傳json
  
  $oOutData=new stdClass();
  $oOutData->iFileCount=$iFileCount;
  $oOutData->strNote=$oJson->strNote;
  
  echo json_encode($oOutData, JSON_UNESCAPED_UNICODE); // 輸出 json 資料

?>