溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

jquery+ajax實(shí)現(xiàn)上傳圖片并顯示上傳進(jìn)度功能【附php后臺(tái)接收】

發(fā)布時(shí)間:2020-08-24 11:11:23 來源:腳本之家 閱讀:133 作者:idjl 欄目:web開發(fā)

本文實(shí)例講述了jquery+ajax實(shí)現(xiàn)上傳圖片并顯示上傳進(jìn)度功能。分享給大家供大家參考,具體如下:

jquery上傳文件用的formdata,上傳進(jìn)度條需要添加xhr的onprogress

html代碼如下:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>Ding Jianlong Html</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/layer/2.3/skin/layer.css" rel="external nofollow" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/layer/2.3/layer.js"></script>
</head>
<body>
 <!-- 外層div 進(jìn)度條的整體視覺和位置設(shè)置 -->
  <div >
  <!-- 內(nèi)層div 逐漸遞增的進(jìn)度條 -->
    <div id="jdt" ></div>
  </div>
  <p>總大小<span id="total"></span>;已上傳<span id="loaded"></span>;</p><br>
  <form id="mainForm">
    選擇文件:<input type="file" name="file">
    <input type="button" value="上傳" onclick="upload()">
  </form>
<script>
  var uploading = false;
 function upload(){
    //首先封裝一個(gè)方法 傳入一個(gè)監(jiān)聽函數(shù) 返回一個(gè)綁定了監(jiān)聽函數(shù)的XMLHttpRequest對(duì)象
    var xhrOnProgress=function(fun) {
      xhrOnProgress.onprogress = fun; //綁定監(jiān)聽
      //使用閉包實(shí)現(xiàn)監(jiān)聽綁
      return function() {
        //通過$.ajaxSettings.xhr();獲得XMLHttpRequest對(duì)象
        var xhr = $.ajaxSettings.xhr();
        //判斷監(jiān)聽函數(shù)是否為函數(shù)
        if (typeof xhrOnProgress.onprogress !== 'function')
          return xhr;
        //如果有監(jiān)聽函數(shù)并且xhr對(duì)象支持綁定時(shí)就把監(jiān)聽函數(shù)綁定上去
        if (xhrOnProgress.onprogress && xhr.upload) {
          xhr.upload.onprogress = xhrOnProgress.onprogress;
        }
        return xhr;
      }
    }
    var data = new FormData($('#mainForm')[0]); //要加【0】
    console.log(data);
    if(uploading){
      layer.alert("文件正在上傳中,請(qǐng)稍候");
      return false;
    }
    $.ajax({
      type: 'POST',
      url: 'upload_file.php',  //當(dāng)前路徑
      data: data,
      dataType: 'json',
      processData: false,  //序列化,no
      contentType: false,  //不設(shè)置內(nèi)容類型
      beforeSend: function(){
        uploading = true;
      },
      //進(jìn)度條要調(diào)用原生xhr
      xhr:xhrOnProgress(function(evt){
        var percent = Math.floor(evt.loaded / evt.total*100);//計(jì)算百分比
        console.log(percent);
        // 設(shè)置進(jìn)度條樣式
        $('#jdt').css('width',percent * 3 + 'px');
        $('#jdt').css('background','skyblue');
        //顯示進(jìn)度百分比
        $('#jdt').text(percent+'%');
        $('#loaded').text(evt.loaded/1024 + 'K');
        $('#total').text(evt.total/1024 + 'K');
      }),
      success: function (data) {
        if (data.code == 200) {
          layer.msg(data.message, {icon: 1, time: 1000});
          //成功后關(guān)閉修改頁
          setTimeout(function(){
            var index = parent.layer.getFrameIndex(window.name); //先得到當(dāng)前iframe的索引
            parent.layer.close(index);  //在執(zhí)行關(guān)閉
          } ,2000);
          //還有刷新下iframe的界面
          parent.location.reload();
        } else {
          layer.msg(data.message, {icon: 2, time: 3000});
        }
        uploading = false;
      },
      error: function (data) {
        alert('服務(wù)異常,請(qǐng)稍后重試');
        console.log(data);
      }
    });
  }
</script>
</body>
</html>

php代碼如下:

<?php
header('content-type:text/html;charset=utf-8');
if ($_FILES["file"]["error"] > 0)
{
 echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
 // 文件中文轉(zhuǎn)碼
 //iconv('utf-8', 'gbk', $_FILES["file"]["name"]);
  //取出后綴名
  $ext = strrchr($_FILES["file"]["name"],'.');
  move_uploaded_file($_FILES["file"]["tmp_name"],
   "upload/" . uniqid() . $ext);
  $arr['code'] = 666;
  $arr['message'] = "已經(jīng)保存到: " . "upload/" . uniqid() . $ext;
  echo json_encode($arr);die;
}

參考資料: https://www.jb51.net/article/94853.htm

更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jquery中Ajax用法總結(jié)》、《jQuery擴(kuò)展技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery常見經(jīng)典特效匯總》及《jquery選擇器用法總結(jié)》

希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI