ajax利用FormData、FileReader实现多文件上传php获取
更新:HHH   时间:2023-1-7


一、FormData方式

  1. 前台代码(注意,不需要用到form标签):
    a. html部分:

    b. js部分:

    c. 完整代码:
    <input type="file" multiple id="lee_file">
    <input type="text" id="lee_text" value="test">
    <input type="button" value="Upload" id="lee_button">
    <script>
    function loadDoc(file,data,async=true){
    if(window.XMLHttpRequest){  // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }else{  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(async === true){
      xmlhttp.onreadystatechange = function(){
          if(xmlhttp.readyState < 4){
              // 加载中
          }else if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
              // 成功
              xmlDoc=xmlhttp.responseText;
              return xmlDoc
          }else{
              // 失败
              xmlhttp.abort()
              return
          }
      }
    }
    xmlhttp.open("POST",file,async);
    xmlhttp.send(data);
    if(async === false){
      xmlDoc=xmlhttp.responseText;
      return xmlDoc
    }
    }
    function getEle(id){
    var ele = document.getElementById(id)
    return ele
    }
    function sendFile() {
    var lee_file = getEle('lee_file');
    var lee_text = getEle('lee_text');
    var form_data = new FormData();
    for (var i in lee_file.files) {
    form_data.append('pics[]', lee_file.files[i]);
    }
    form_data.append('text', lee_text.value);
    loadDoc('test.php',form_data)
    }
    var lee_button = getEle('lee_button');
    lee_button.onclick = function(){
    sendFile()
    }
    </script>
  2. php获取(用 $_FILE 获取):

    完整代码:
    <?php
    header('Access-Control-Allow-Origin: *');
    var_dump($_POST);
    var_dump($_FILES);

    二、FileReader+FormData+base64

  3. 前台代码:
    a. html代码:

    b. js代码:

    c. 完整代码:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title></head>
    <body>
    <form>
    <input type="file" multiple id="lee_file">
    <input type="button" value="上传图片" id="lee_button">
    <img src="" alt="" id="lee_img">
    </form>
    <script>
    function loadDoc(file,data,async=true){
    if(window.XMLHttpRequest){  // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }else{  // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(async === true){
      xmlhttp.onreadystatechange = function(){
          if(xmlhttp.readyState < 4){
              // 加载中
          }else if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
              // 成功
              xmlDoc=xmlhttp.responseText;
              return xmlDoc
          }else{
              // 失败
              xmlhttp.abort()
              return
          }
      }
    }
    xmlhttp.open("POST",file,async);
    xmlhttp.send(data);
    if(async === false){
      xmlDoc=xmlhttp.responseText;
      return xmlDoc
    }
    }
    function getEle(id){
    var ele = document.getElementById(id)
    return ele
    }
    lee_button = getEle('lee_button')
    function sendFile() {
    var lee_file = getEle('lee_file').files;
    var lee_text = getEle('lee_text');
    for (var i = 0; i < lee_file.length; i++) {
      file = lee_file[i];
      var form_data = new FormData();
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onloadend = function() { // onload代表文件读取成功
        getEle('lee_img').setAttribute('src',reader.result);
        form_data.append('pic', reader.result);
        loadDoc('test.php',form_data)
      }
    }
    }
    lee_button.onclick = function() {
    sendFile();
    }
    </script>
    </body>
    </html>
  4. php代码(用 $_POST 获取):
    a. 允许跨域:

    b. 将前台post过来的数据保存为临时文件:

    c. 获取文件真实后缀函数:

    d. 将临时文件保存为带真实后缀的文件:

    e. 完整代码:
    <?php
    header('Access-Control-Allow-Origin:*');  
    /*
    * 将流文件保存为临时文件
    * @param   stream  base64输入流
    * @param   tmpname 临时文件路径
    */  
    function uploadBase64($stream) {
        if (empty($stream)) return false;
        if (preg_match('/^(data:(\s)?(image|img)\/(\w+);base64,)/', $stream, $str)) {
            $suffix = "tmp";
            $tmpname = rand(1000, 9999) . ".{$suffix}";
            if (file_put_contents($tmpname, base64_decode(str_replace($str[1], '', $stream)))) {
                return $tmpname;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } 
    /*
    获取图片真实后缀
    @param   filename    文件名
    @param   suffix      文件真实后缀(.jpg .png .gif)
    */   
    function getSuffix($fileName) {
    $file = fopen($fileName, "rb");
    $bin = fread($file, 2); // 只读2字节
    fclose($file);
    $strInfo = @unpack("C2chars", $bin);
    $typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
    $suffix = "unknow";
    if($typeCode == 255216){
        $suffix = "jpg";
    }elseif($typeCode == 7173){
        $suffix = "gif";
    }elseif($typeCode == 13780){
        $suffix = "png";
    }elseif($typeCode == 6677){
        $suffix = "bmp";
    }elseif($typeCode == 7798){
        $suffix = "exe";
    }elseif($typeCode == 7784){
        $suffix = "midi";
    }elseif($typeCode == 8297){
        $suffix = "rar";
    }elseif($typeCode == 7368){
        $suffix = "mp3";
    }elseif($typeCode == 0){
        $suffix = "mp4";
    }elseif($typeCode == 8273){
        $suffix = "wav";
    }
    return $suffix;
    }
返回web开发教程...