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

php+ajax實(shí)現(xiàn)異步上傳文件或圖片功能

 更新時(shí)間:2017年07月18日 14:59:21   作者:PajamaCat  
這篇文章主要為大家詳細(xì)介紹了php+ajax實(shí)現(xiàn)異步上傳文件或圖片功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文為大家分享了ajax異步上傳文件或圖片功能的具體代碼,供大家參考,具體內(nèi)容如下

//html代碼

<form enctype="multipart/form-data" id="upForm">
 <input type="file" name="file" ><br><br>
 <input type="button" value="提交">
</form>
<div class="picDis">
 <img src="" alt="">
</div>


//js代碼

(':button').click(function(event) {
  //formdata儲(chǔ)存異步上傳數(shù)據(jù)
 var formData = new FormData($('form')[0]);
 formData.append('file',$(':file')[0].files[0]);
 //坑點(diǎn): 無論怎么傳數(shù)據(jù),console.log(formData)都會(huì)顯示為空,但其實(shí)值是存在的,f12查看Net tab可以看到數(shù)據(jù)被上傳了
 $.ajax({
  url:'formtest.php',
  type: 'POST',
  data: formData,
  //這兩個(gè)設(shè)置項(xiàng)必填
  contentType: false,
  processData: false,
  success:function(data){
  console.log(data)
  var srcPath = data;
  console.log();
     //注意這里的路徑要根據(jù)自己的儲(chǔ)存文件的路徑設(shè)置
  $('.picDis img').attr('src', '..'+srcPath);
  }
 })
 });

php:

<?php 

$upFile = $_FILES['file'];

/**
* 創(chuàng)建文件夾函數(shù),用于創(chuàng)建保存文件的文件夾
* @param str $dirPath 文件夾名稱
* @return str $dirPath 文件夾名稱
*/
function creaDir($dirPath){
 $curPath = dirname(__FILE__);
 $path = $curPath.'\\'.$dirPath;
 if (is_dir($path) || mkdir($path,0777,true)) {
  return $dirPath;
 }
}

//判斷文件是否為空或者出錯(cuò)
if ($upFile['error']==0 && !empty($upFile)) {
 $dirpath = creaDir('upload');
 $filename = $_FILES['file']['name'];
 $queryPath = './'.$dirpath.'/'.$filename;
 //move_uploaded_file將瀏覽器緩存file轉(zhuǎn)移到服務(wù)器文件夾
 if(move_uploaded_file($_FILES['file']['tmp_name'],$queryPath)){
  echo $queryPath;
 }
}

 ?>

點(diǎn)擊上傳圖片并發(fā)送后, 可以看到頁面上顯示出圖片, 查看本地文件夾可以看到文件也已儲(chǔ)存到服務(wù)器.

在客戶端實(shí)現(xiàn)異步上傳的關(guān)鍵在于FormData,關(guān)于這部分這里有詳細(xì)介紹: FormData()

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

相關(guān)文章

最新評論