檔案上傳 (教學示範)

建立 html 的表
<form action="<?php echo basename(__FILE__); ?>" method="post" enctype="multipart/form-data">
<fieldset><legend>上傳檔案</legend>
<ol>
<li><label for="upload1">上傳:</label><input type="file" id="upload1" name="upload1" accept="image/*"></li>
<li><button type="submit" name="sending" value="1">送出</button></li>
</ol>
</fieldset>
</form>
取得上傳檔案相關資訊
<?php
if(filter_has_var(INPUT_POST,'sending')){
 echo '<p>';
 var_export($_FILES);
 echo '</p>';
}
?>

結果像: (假設上傳檔名 pic.jpg)

array ( 'upload1' => array ( 'name' => 'pic.jpg', 'type' => 'image/jpeg', 'tmp_name' => 'C:\\server\\tmp\\php1EB7.tmp', 'error' => 0, 'size' => 576523, ), )
防止意外上傳大檔案
<form action="<?php echo basename(__FILE__); ?>" method="post" enctype="multipart/form-data">
<fieldset><legend>上傳檔案</legend>
<ol>
<li><label for="upload1">上傳:</label><input type="hidden" name="MAX_FILE_SIZE" value="2000000"><input type="file" id="upload1" name="upload1" accept="image/*"></li>
<li><button type="submit" name="sending" value="1">送出</button></li>
</ol>
</fieldset>
</form>

注意這個輸入項須產生在 file input 元素之前

存入指定資料夾
<?php
if(filter_has_var(INPUT_POST,'sending')){
 if($_FILES['upload1']['error']==UPLOAD_ERR_OK){
  $fname='./upload/'.$_FILES['upload1']['name'];
  move_uploaded_file($_FILES['upload1']['tmp_name'],$fname);
 }
}
?>

注意 move_uploaded_file 無法轉成中文檔名

參考資源

更新日期:

google 論壇

App javascript (groups.google.com/group/app-javascript/)