PHP+Ajax實現檔案無重新整理上傳檔案代碼

來源:互聯網
上載者:User

PHP + jQuery Ajax檔案上傳執行個體。因為看到一些朋友詢問如何?PHP環境下的網頁上傳功能,自己這幾天剛用了jQuery_upload_multiple上傳外掛程式,所以在這裡把用法給大家說一下。

要實現基於這個外掛程式的上傳功能,其實挺簡單,需要jquery就行了,另外還有一個上傳檔案時的PHP程式,費話不多說,先看下面的HTML,也就是帶有上傳表單,讓使用者選擇上傳檔案的頁面:

 

 代碼如下 複製代碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Easy Ajax FormData Upload Multiple Images</title>
<script type="text/javascript" src="/ajaxjs/jquery-1.6.2.min.js"></script><!--此處可引用你實際路徑的jquery外掛程式-->
</head>
<body>
<style>
 #feedback{width:1200px;margin:0 auto;}
 #feedback img{float:left;width:300px;height:300px;}
 #ZjmainstaySignaturePicture,#addpicContainer{float:left;width: 100%;}
 #addpicContainer{margin-left:5px;}
 #ZjmainstaySignaturePicture img{width: 535px;}
 #addpicContainer img{float: left;}
 .loading{display:none;background:url("yun_qi_img/ui-anim_basic_16x16.gif") no-repeat scroll 0 0 transparent;float: left;padding:8px;margin:18px 0 0 18px;}
</style>
<div id="addpicContainer">
 <!-- 利用multiple="multiple"屬性實現添加多圖功能 -->
 <!-- position: absolute;left: 10px;top: 5px;只針對本用例將input隱至圖片底下。-->
 <!-- height:0;width:0;z-index: -1;是為了隱藏input,因為Chrome下不能使用display:none,否則無法添加檔案 -->
 <!-- onclick="getElementById('inputfile').click()" 點擊圖片時則點擊添加檔案按鈕 -->
 <img onclick="getElementById('inputfile').click()" style="cursor:pointer;border: 1px solid #AABBCC;" title="點擊添加圖片" alt="點擊添加圖片" src="yun_qi_img/addfile.jpg">
 <input type="file" multiple="multiple" id="inputfile" style="height:0;width:0;z-index: -1; position: absolute;left: 10px;top: 5px;"/>
 <span class="loading"></span>
</div>
<div id="feedback"></div><!-- 響應返回資料容器 -->
<script type="text/javascript">
$(document).ready(function(){
 //回應檔添加成功事件
 $("#inputfile").change(function(){
  //建立FormData對象
  var data = new FormData();
  //為FormData對象添加資料
  $.each($('#inputfile')[0].files, function(i, file) {
   data.append('upload_file'+i, file);
  });
  $(".loading").show(); //顯示載入圖片
  //發送資料
  $.ajax({
   url:'submit_form_process.php',
   type:'POST',
   data:data,
   cache: false,
   contentType: false, //不可缺參數
   processData: false,  //不可缺參數
   success:function(data){
    data = $(data).html();
    //第一個feedback資料直接append,其他的用before第1個( .eq(0).before() )放至最前面。
    //data.replace(/&lt;/g,'<').replace(/&gt;/g,'>') 轉換html標籤,否則圖片無法顯示。
    if($("#feedback").children('img').length == 0) $("#feedback").append(data.replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
    else $("#feedback").children('img').eq(0).before(data.replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
    $(".loading").hide(); //載入成功移除載入圖片
   },
   error:function(){
    alert('上傳出錯');
    $(".loading").hide(); //載入失敗移除載入圖片
   }
  });
 });
});
</script>
</body>
</html>

接下來是上傳圖片的PHP檔案代碼:檔案名稱:submit_form_process.php

 代碼如下 複製代碼

<?php
header('content-type:text/html charset:utf-8');
$dir_base = "./files/"; //檔案上傳根目錄
//沒有成功上傳檔案,報錯並退出。
if(empty($_FILES)) {
 echo "<textarea><img src='{$dir_base}error.jpg'/></textarea>";
 exit(0);
}
$output = "<textarea>";
$index = 0; //$_FILES 以檔案name為數組下標,不適用foreach($_FILES as $index=>$file)
foreach($_FILES as $file){
 $upload_file_name = 'upload_file' . $index;//對應index.html FomData中的檔案命名
 $filename = $_FILES[$upload_file_name]['name'];
 $gb_filename = iconv('utf-8','gb2312',$filename); //名字轉換成gb2312處理
 //檔案不存在才上傳
 if(!file_exists($dir_base.$gb_filename)) {
  $isMoved = false;  //預設上傳失敗
  $MAXIMUM_FILESIZE = 1 * 1024 * 1024;  //檔案大小限制 1M = 1 * 1024 * 1024 B;
  $rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i";
  if ($_FILES[$upload_file_name]['size'] <= $MAXIMUM_FILESIZE &&
   preg_match($rEFileTypes, strrchr($gb_filename, '.'))) { 
   $isMoved = @move_uploaded_file ( $_FILES[$upload_file_name]['tmp_name'], $dir_base.$gb_filename);  //上傳檔案
  }
 }else{
  $isMoved = true;//已存在檔案設定為上傳成功
 }
 if($isMoved){
  //輸出圖片檔案<img>標籤
  //註:在一些系統src可能需要urlencode處理,發現圖片無法顯示,
  //    請嘗試 urlencode($gb_filename) 或 urlencode($filename),不行請查看HTML中顯示的src並酌情解決。
  $output .= "<img src='{$dir_base}{$filename}' title='{$filename}' alt='{$filename}'/>";
 }else {
  $output .= "<img src='{$dir_base}error.jpg' title='{$filename}' alt='{$filename}'/>";
 }
 $index++;
}
echo $output."</textarea>";

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.