php 如何上传文件到服务器宽度media_handle_upload?

gwo2fgha  于 2023-11-16  发布在  PHP
关注(0)|答案(1)|浏览(94)

我在创建帖子时遇到了问题,特别是在上传帖子图像时。这个想法是,未经授权的用户提交了一个竞赛申请。成功付款后,我将表单数据以JSON格式发送给apache。

  1. payData用于付款:
function getPayData() {
    
        var payData = {};
    
        
        payData['gallery-parent-id'] = {};
        payData['gallery-parent-id']['value'] = form.dataset.parent;
        payData['form-id'] = {};
        payData['form-id']['value'] = form.dataset.id;
        
        // return payData
        return payData;
    }

字符串

  1. Ajax付款方式:
$.ajax({
        url: url,
        type: 'POST',
        data: payData,
        success: function(response) {

            var response_end = JSON.parse(response);

            var confirmationToken = response_end.confirmation_token;
            var order_id = response_end.id;
            var amount = response_end.amount;
            if (confirmationToken) {
                const checkout = new window.YooMoneyCheckoutWidget({
                    customization: {
                        control_primary: '#81fdc5'
                    },
                    error_callback: function(error) {
                    }
                });

                checkout.on('success', () => {
                    formData.append('order id:', order_id);
                    formData.append('amount:', amount);
                    
                    const success_url = '/pay/success-pay-handler.php';

                    $.ajax({
                        url: success_url,
                        type: 'POST',
                        data: formData,
                        cache       : false,
                        dataType    : 'json',
                        processData : false,
                        contentType : false,
                        success: function(response) {

                            console.log(response);
                            //message.classList.add('show');
                        },
                        error: function(response) {
                            // Обработка ошибки
                            console.log(response);
                            console.error('Error data send.');
                        }
                    });
        
                    //del widget
                    checkout.destroy();
                });

        
                checkout.render('payment-form');
                setTimeout(function() {
                    //form.classList.add('in-process');
                }, 300);
            } else {
                console.log('No token')
            }
          

        },
        error: function() {
          // Error hand
          console.error('Errror data send.');
        }
    });


1.表格数据:

formData = new FormData();

    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];
        if (element.type === 'text' || element.type === 'textarea' || element.type === 'number' || element.type === 'mail') {
                    
            var label = document.querySelector('label[for="' + element.name + '"]');

            var name = element.name;

            var title = label.textContent.trim();
            var value = element.value;

            var valueWithLabel = [title, value];

            formData.append(name, valueWithLabel);

        } else if (element.type === 'file') {

            var name = element.name;

            formData.append(name, element.files[0]);
        }
    }

  1. Ajax for formData
$.ajax({
                        url: success_url,
                        type: 'POST',
                        data: formData,
                        cache       : false,
                        dataType    : 'json',
                        processData : false,
                        contentType : false,
                        success: function(response) {
                            console.log(response);
                        },
                        error: function(response) {
                            console.log(response);
                            console.error('Error data send.');
                        }
                    });


我成功地在PHP中接收了表单数据。首先,我包含了操作所需的文件:

require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');


然后我从aplog中检索数据,一个使用常规数据- $formData,另一个使用文件- $formFiles。

$formData = $_POST;
    $formFiles = $_FILES;


接下来,我遍历了表单字段+ ACF数组。帖子成功创建,所以我还没有发送整个代码。然后,当我试图上传帖子的图像时,问题就开始了。我遍历了$_FILES,将值存储在$artFiles数组中。

$artFiles = array();
    
    foreach ($formFiles as $key => $file) {
        if (strpos($key, "art-file-") === 0) {
            $artFileNumber = substr($key, strlen("art-file-"));
            $artFiles[$artFileNumber] = $file;
        }
    }


My $artNames foreach:

foreach ($formData as $key => $value) {
        if (strpos($key, "art-name-") === 0) {
            // Разбиваем строку значения по запятой
            $parts = explode(',', $value);
    
            // Проверяем, что в массиве $parts есть второй элемент
            if (isset($parts[1])) {
                $artNameNumber = str_replace("art-name-", "", $key);
                $artName = trim($parts[1]);
    
                // Добавляем значения в соответствующие массивы
                $artNames[$artNameNumber] = $artName;
            }
    }


创建帖子:

foreach ($artNames as $artNameNumber => $artName) {
        $artHeight = isset($artHeights[$artNameNumber]) ? $artHeights[$artNameNumber] : '';
        $artWidth = isset($artWidths[$artNameNumber]) ? $artWidths[$artNameNumber] : '';
        $artMaterial = isset($artMaterials[$artNameNumber]) ? $artMaterials[$artNameNumber] : '';
        $artDescr = isset($artDescrs[$artNameNumber]) ? $artDescrs[$artNameNumber] : '';
        $artFile = isset($artFiles[$artNameNumber]) ? $artFiles[$artNameNumber] : '';

        $artFileInfo = $artFile['name'] . ' : ' . $artFile['tmp_name'] . ' : ' . $artFile['size']; // OK, it's work!
        $post_data = array(
            'post_type' => 'gallery',
            'post_status' => 'draft',
            'post_parent' => $parent_page_id,
            'post_title'     => $artName,
            'post_content' => $artFileInfo // For tests, it's OK: food-cat-image-2.jpg : /tmp/phpos4nzn : 2937708
        );

        $post_id = wp_insert_post($post_data);
    
        update_post_meta($post_id, '_wp_page_template', 'single-cat-gallery.php');

        // Upload File

        $attachment_id = media_handle_upload( $artFile, $post_id ); // Not work
        

        if ( is_wp_error( $attachment_id ) ) {
            $error_message = $attachment_id->get_error_message();
            echo json_encode( array( 'error' => $error_message ) );
        } else {
            echo json_encode( array( 'success' => 'File Upload Complete! ID:' . $attachment_id ) );
        }

        update_post_meta( $post_id, '_thumbnail_id', $attachment_id ); // OK, it's work!

        //
    
        if( is_wp_error($post_id) ){    

        } else {
            if (function_exists('update_field')) {

                // Acf fields
                
            }
        }
    
    }


字符串

$artFileInfo = $artFile['name'] . ' : ' . $artFile['tmp_name'] . ' : ' . $artFile['size']

cat-image-2.jpg : /tmp/phpos4nzn : 2937708


我尝试了很多不同的选择,但没有一个有帮助。
也许这个信息可以帮助:我添加了一个检查is_wp_error并得到以下消息:

responseText : 
"{\"error\":\"Specified file failed upload test.\"}{\"error\":\"Specified file failed upload test.\"}"
status : 200
statusText : "parsererror"


更多信息:
var_dump($_FILES):

array(2) {
  ["art-file-1"]=>
  array(5) {
    ["name"]=>
    string(18) "food-cat-image.jpg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/php3xJrf3"
    ["error"]=>
    int(0)
    ["size"]=>
    int(272437)
  }
  ["art-file-2"]=>
  array(5) {
    ["name"]=>
    string(17) "video-preview.jpg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpGsRXSE"
    ["error"]=>
    int(0)
    ["size"]=>
    int(100533)
  }
}


我已经重读了很多类似的题目,没有任何解决方案对我有帮助。请保存我。
我试着在我的PHP处理程序中添加:

require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

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
使用不同的功能进行上传
我尝试在media_handle_upload函数中指定不同的值:
$attachment_id = media_handle_upload($artFile 'name']/$artFile 'tmp_name']/$_FILES' art-file-1'].,$post_id);
所有php.info设置都正常。

UPD:

非常感谢您的关注@CBroe!
我们的$artFile似乎是一个数组-$_FILES数组的条目之一;但media_handle_upload需要一个字符串$file_id作为第一个参数,即$_FILES数组中文件的键。您应该调用它来处理第一个上传的文件的值是art-file-1
对于我的例子所有的问题这:

$attachment_id = media_handle_upload( $artFile, $post_id );

正确的选项

$attachment_id = media_handle_upload( 'art-file-' . $artNameNumber, $post_id );
q9rjltbz

q9rjltbz1#

我用这个代码希望对你有帮助

// it allows us to use wp_handle_upload() function
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');

    $upload = wp_handle_upload(
        $_FILES['uploaded'],
        array('test_form' => false)
    );

    if (!empty($upload['error'])) {
        wp_send_json( 'error in upload' );
    }

    // it is time to add our uploaded image into WordPress media library
    $attachment_id = wp_insert_attachment(
        array(
            'guid'           => $upload['url'],
            'post_mime_type' => $upload['type'],
            'post_title'     => basename($upload['file']),
            'post_content'   => '',
            'post_status'    => 'inherit',
        ),
        $upload['file'],
        $postId //when i create post by wp_insert_post postId return;
    );

    if (is_wp_error($attachment_id) || !$attachment_id) {
        wp_send_json( 'error in upload' );
    }

    set_post_thumbnail($postId, $attachment_id);

字符串

相关问题