//單文件上傳,個人業務需求中限制了必須上傳圖片 <input type="file" name="singlename" accept="image/*"> //多文件上傳 <input type="file" name="multiename[]" multiple="multiple"> //注意同時應該是form節點上加上enctype="multipart/form-data"屬性,不然文件將沒法上傳
$singlefile = $_FILES['singlename']; $multifiles = $_FILES['multiname'];
在這裏,須要注意單個文件和多個文件的處理方式是不一樣的,處理方式參照第四步,咱們經過print_r到前端能夠看到其格式php
//這是單個文件的輸出結果 Array ( [name] => 12345677889.jpg [type] => image/jpeg [tmp_name] => /tmp/phptyS5oO [error] => 0 [size] => 32920 ) //這是多個文件的輸出結果 Array ( [name] => Array ( [0] => 12345677889.jpg [1] => attach_ico.png ) [type] => Array ( [0] => image/jpeg [1] => image/png ) [tmp_name] => Array ( [0] => /tmp/phpDXQEa5 [1] => /tmp/php3Q09Xd ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 32920 [1] => 1864 ) )
function my_handle_attachment($file_handler,$post_id,$set_thu=false) { // check to make sure its a successful upload if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attach_id = media_handle_upload( $file_handler, $post_id ); if ( is_numeric( $attach_id ) ) { update_post_meta( $post_id, '_my_file_upload', $attach_id ); } return $attach_id; }
四、調用自定義函數便可完成上傳 前端
若是是單個文件那麼咱們的調用將會很簡單函數
$attachment_id = my_handle_attachment('singlename',$you_post_id);
在這裏咱們須要注意,經過 第二步咱們能夠看到單個文件和多個文件的輸出結果格式的差別,所以咱們須要對多個文件進行一下處理,讓他成爲單個文件的格式以完成上傳post
$files = $_FILES["multiname"]; foreach ($files['name'] as $key => $value) { if ($files['name'][$key]) { $file = array( 'name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key] ); $_FILES = array ("singlefile" => $file); $attachment_id = my_handle_attachment('singlefile',$you_post_id); } } }