PHP檔案下傳

來源:互聯網
上載者:User
PHP檔案上傳

一、普通檔案上傳方式

使用原生態的php上傳檔案。

(1)前端代碼

      

?

(2)php代碼(upload_file.php)

     0) {          echo "Return Code: " . $_FILES["file"]["error"] . "
"; }else { echo "Upload: " . $_FILES["file"]["name"] . "
"; echo "Type: " . $_FILES["file"]["type"] . "
"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
"; if (file_exists("upload/" . $_FILES["file"]["name"])){ echo $_FILES["file"]["name"] . " already exists. "; }else{ move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } }else { echo "Invalid file"; } ?>
?

?

?

二、非同步檔案上傳方式

目的是盡量少使用外掛程式。於是使用iframe非同步上傳檔案

?

(1)前端html

             

?

    function startUpload() {          var spanObj = document.getElementById("info");          spanObj.innerHTML = " 開始上傳";          document.getElementById("upForm").sumbit();      }      //回調      function stopUpload(responseText){          var spanObj = document.getElementById("info");          spanObj.innerHTML = "上傳成功";          spanObj.innerHTML = responseText;      }  

?

(2)伺服器端代碼

    $file = $_FILES['myfile'];      $fileName = uploadFile($file);      //$result = readFromFile("../upload/" . $fileName);      echo "";            function uploadFile($file) {          // 上傳路徑               $destinationPath = "../upload/";          if (!file_exists($destinationPath)){              mkdir($destinationPath , 0777);          }          //重新命名          $fileName = date('YmdHis') . '_' . iconv('utf-8' , 'gb2312' , basename($file['name']));          if (move_uploaded_file($file['tmp_name'], $destinationPath . $fileName)) {              return iconv('gb2312' , 'utf-8' , $fileName);          }          return '';      }  

?

    //代碼注釋      /*     1,關於basename方法     $path = "/testweb/home.php";     //顯示帶有副檔名的檔案名稱     echo basename($path);     //顯示不帶有副檔名的檔案名稱     echo basename($path,".php");          2,關於iconv     iconv('gb2312' , 'utf-8' , $fileName);//將$fileName從gb2312轉為utf-8格式。     註:該函數需要開啟php.ini裡面的php_iconv.dll          3,關於$_FILES['myfile']     $_FILES相當於一個二維數組,而$_FILES['myfile']相當於一個一維數組。所以可以     $f = $_FILES['myfile'];     echo $f['name'];          如果直接存取該$_FILES['myfile'],則會報Undefined index: myfile。此時加上     if(!isset($_FILES['myfile'])){         die('上傳檔案不存在!');     }     */  
?
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.