使用media_handle_upload上传多个文件


16

我有一个WordPress表单插件,我media_handle_upload用来上传文件并直接获得ID,并将其ID作为元日期附加到帖子中,我使用以下方法来做到这一点:

表单字段的HTML是:

<input type="file" name="my_file_upload" id="my_file_upload">

而PHP代码是:

$attach_id = media_handle_upload( 'my_file_upload', $post_id );
if ( is_numeric( $attach_id ) ) {
    update_post_meta( $post_id, '_my_file_upload', $attach_id );
}

一切都正常进行。

现在,我正在尝试上传多个文件,我的HTML代码是:

<input type="file" name="my_file_upload[]" id="my_file_upload[]" multiple="multiple">

但是我无法使该media_handle_upload功能与多个文件上传一起使用。

任何帮助将不胜感激。


使用的foreach上传多个,IAM移动现在这样icant后的完整代码
黑幕中号Rasmy

我尝试了许多foreach循环,但没有一个起作用。
工程师MTH

Answers:


14

如果您在开始时使用自定义模板,则在这里

<?php
 if( 'POST' == $_SERVER['REQUEST_METHOD']  ) {
if ( $_FILES ) { 
    $files = $_FILES["my_file_upload"];  
    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 ("my_file_upload" => $file); 
                foreach ($_FILES as $file => $array) {              
                    $newupload = my_handle_attachment($file,$pid); 
                }
            } 
        } 
    }

}
?>

在function.php中

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;
}

网址http://www.kvcodes.com/2013/12/create-front-end-multiple-file-upload-wordpress/


感谢您的代码,我正在用它来提交帖子。我想知道如何验证上传的文件。有办法吗?
sb0k 2015年

3
这不会覆盖全局$ _FILES变量吗?
ReLeaf

@ReLeaf这应该覆盖全局$ _FILES变量。media_handle_upload()寻找$_FILES[$file_handler]
Andy Macaulay-Brook '18

尝试上传多个文件(单个文件即可)时,此代码段非常完美,除了适用于Android WebView之外。
Rollor

7

如果要在不使用功能文件的情况下实现此功能,则可以使用我提供的简化版本。这是经过测试的代码,效果100%

<form id="file_upload" method="post" action="#" enctype="multipart/form-data">
     <input type="file" name="my_file_upload[]" multiple="multiple">
     <input name="my_file_upload" type="submit" value="Upload" />
</form>

将PHP代码放在提交发生的页面上。就我而言,与表单操作在同一页面上设置为“#”

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );

    $files = $_FILES["my_file_upload"];
    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("upload_file" => $file);
            $attachment_id = media_handle_upload("upload_file", 0);

            if (is_wp_error($attachment_id)) {
                // There was an error uploading the image.
                echo "Error adding file";
            } else {
                // The image was uploaded successfully!
                echo "File added successfully with ID: " . $attachment_id . "<br>";
                echo wp_get_attachment_image($attachment_id, array(800, 600)) . "<br>"; //Display the uploaded image with a size you wish. In this case it is 800x600
            }
        }
    }
} ?>

表单提交完成后,此方法仅包含所需文件一次,而不是每次通过foreach循环调用函数时都包含所需文件


编辑:我已经摘下了代码$post_thumbnail_id = wp_get_attachment_image_src($attachment_id, array(800, 600));,因为该示例没有必要。但是,如果您希望获取图像的URL,它将对您有所帮助:)
幸运

5

谢谢@ shady-m-rasmy我使用了您提到的代码,似乎第二个foreach循环(在自定义模板部分中,在下面)不是必需的,因为它仅执行一次。

foreach ($_FILES as $file => $array) {              
   $newupload = my_handle_attachment($file,$pid);
} 

所以只剩下

$newupload = my_handle_attachment( "my_file_upload", $pid);

0

同一元密钥的多个条目

$values = [ 'red', 'yellow', 'blue', 'pink' ];
foreach( $values as $value ) {
    // This method uses `add_post_meta()` instead of `update_post_meta()`
    add_post_meta( $item_id, 'color', $value );
}

您能格式化代码并添加说明吗?
Nilambar Sharma

我不确定这是否可以解决这里的问题:最困难的部分似乎是解析提交的文件,而不是将多个文件附加到帖子。
Rup

0

的HTML

<input type="file" id="id_termine_attachment" multiple="multiple" name="id_termine_attachment[]" value="" size="25" />

的PHP

function upload_file($_FILES) {

    if (!empty($_FILES['id_termine_attachment'])) {
        $supported_types = array(
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/msword',
            'image/gif',
            'image/jpeg',
            'image/png',
            'application/zip'
         );

        $file_arr = reArrayFiles($_FILES['id_termine_attachment']);
        $file_urls = [];

        foreach ($file_arr as $file) {
            $arr_file_type = wp_check_filetype(basename($file['name']));
            $uploaded_type = $arr_file_type['type'];
            if (in_array($uploaded_type, $supported_types)) {
                $upload = wp_upload_bits($file['name'], null, file_get_contents($file['tmp_name']));
                if (isset($upload['error']) && $upload['error'] != 0) {
                    wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
                } else {
                    array_push($file_urls, $upload['url']);

                } // end if/else
            } else {
                wp_die("This filetyp is not available!");
            }
        }
        update_post_meta($post_id, 'id_termine_attachment', $file_urls);
    }
}



function reArrayFiles(&$file_post) {
    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.