欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

jQuery+ajax實(shí)現(xiàn)文件上傳功能

 更新時(shí)間:2020年12月22日 08:48:18   作者:李大璟  
這篇文章主要為大家詳細(xì)介紹了jQuery+ajax實(shí)現(xiàn)文件上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

jQuery+ajax實(shí)現(xiàn)文件上傳功能(顯示文件上傳進(jìn)度),供大家參考,具體內(nèi)容如下

具體實(shí)現(xiàn)步驟

1、定義UI結(jié)構(gòu),引入bootstrap的CSS文件和jQuery文件
2、給上傳按鈕綁定點(diǎn)擊事件
3、驗(yàn)證是否選擇了文件
4、向FormData中追加文件
5、使用ajax發(fā)起上傳文件的請(qǐng)求
6、設(shè)置文件的路徑
7、使用xhr獲得文件上傳的進(jìn)度
8、當(dāng)文件上傳完成讓進(jìn)度條顯示綠色

<style>
 #loading {
 width: 20px;
 height: 20px;
 }
 
 #img {
 display: block;
 width: 200px;
 height: 200px;
 border-radius: 50%;
 background-color: #abcdef;
 opacity: .5;
 }
</style>

<body>
 <!--multiple可以選擇多個(gè)文件 -->
 <input type="file" multiple name="" id="ipt" multiple><button id="btn" type="submit">上傳文件</button>
 <img id="loading" src="../img/loading.gif" alt="" style="display: none;">
 <!-- bootstrap中引入條件 -->
 <div class="progress" style="margin-top: 10px;width: 100px;margin-left: 10px;">
 <div id="progress" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
 0%
 </div>
 </div>
 <!-- 顯示上傳到服務(wù)器的圖片 -->
 <img src="" alt="" id="img" style="display: none;">
 <script src="../lib/jquery-1.11.0.min.js"></script>
 <script>
 $(function() {
 $('#btn').on('click', function() {
 // 獲取文件列表
 var file = $('#ipt')[0].files
  // 判斷是否選擇了文件
 if (file.length <= 0) {
  return alert('請(qǐng)上傳文件')
 }
 // 創(chuàng)建formdata
 var fd = new FormData()
  // 向formdata中傳入數(shù)據(jù)
  // fd.append()
  // file是一個(gè)偽數(shù)組
 fd.append('avatar', file[0])
  // 用ajax傳送數(shù)據(jù)
 $.ajax({
  type: 'post',
  url: 'http://www.liulongbin.top:3006/api/upload/avatar',
  // 數(shù)據(jù)不需要編碼
  contentType: false,
  // 數(shù)據(jù)對(duì)象不需要轉(zhuǎn)換成鍵值對(duì)格式
  processData: false,
  data: fd,
  beforeSend: function() {
  $('#loading').show()
  },
  complete: function() {
  $('#loading').hide()
  },
  success: function(res) {
  // 判斷是否接收成功
  if (res.status !== 200) {
  return alert(reg.msg)
  }
  $('#img').attr('src', 'http://www.liulongbin.top:3006' + res['url']).css('display', 'block')

  },
  xhr: function xhr() {
  var xhr = new XMLHttpRequest()
  // 獲取文件上傳的進(jìn)度
  xhr.upload.onprogress = function(e) {
  // e.lengthComputable表示當(dāng)前的進(jìn)度是否是可以計(jì)算,返回布爾值
  if (e.lengthComputable) {
   // e.loaded表示下載了多少數(shù)據(jù), e.total表示數(shù)據(jù)總量
   var percentComplete = Math.ceil((e.loaded / e.total) * 100)
   // 讓進(jìn)度條的寬度變化
   $('#progress').css('width', percentComplete)
   // 在進(jìn)度條中顯示百分比
   $('#progress').html(percentComplete + 'px')
  }
  }
  // 文件加載完成
  xhr.upload.onload = function() {
  $('#progress').removeClass('progress-bar progress-bar-striped').addClass('progress-bar progress-bar-success')
  }
  return xhr
  }

 })

 })

 })
 </script>
</body>

效果演示(slow3g狀態(tài))

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論