访问Wordpress Rest API路由中的FormData对象,通过 AJAX 发送

amrnrhlw  于 2022-12-22  发布在  WordPress
关注(0)|答案(1)|浏览(159)

我有一个输入字段,其中的“类型文件”,这是用户可以添加图像。我已经添加到“FormControl对象”的图像。我现在的问题是我如何在我的WordPress的休息函数得到我的文件。所以我可以把它移到我的文件系统。请看下面的代码:
//网页

<div class="column-one">
    <input type="file" name="employee-photo" id="employee-photo"/>
      <div class="upload-photo-warning-msg-container">
         <div class="msg">
         </div>
      </div>
</div>

//js

$('.upload-photo-container #employee-photo').on('change', function(){
    const photo = this.files[0];
    const formData = new FormData();
    formData.append("employeePhoto", photo);
    $.ajax({
       type: 'POST',
           url: myAjax.restURL + 'app/v1/uploadEmployeePhoto',
           data: formData,
           success: function(response){
              msg.empty();
              msg.append($('<p id="required"></p>').text('Uploaded Photo'));
              console.log('SUCCESS RESPONSE: ', response);
           },
           error: function (xhr, ajaxOptions, thrownError) {
           },
           complete: function(data){
           }
     });
 });

//route.php

function upload_employee_photo($request){
   //access the data here so i could do something like
   //$location = './img/';  
   //move_uploaded_file($_FILES["employee-photo"]["tmp_name"], $location);
}

有没有人能在这件事上给予我一点帮助。我会非常感激的,我一直在为这件事挣扎,在过去的日子里。

icnyk63a

icnyk63a1#

请尝试以下操作:
编辑您的JS函数:

$('.upload-photo-container #employee-photo').on('change', function(){
    const photo = this.files[0];
    const formData = new FormData();
    formData.append("employeePhoto", photo);
    $.ajax({
        type: 'POST',
        url: myAjax.restURL + 'app/v1/uploadEmployeePhoto',
        method: 'POST',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-WP-Nonce', localized.nonce);
        },
        data: formData,
        processData: false,
        contentType: false,
        success: function(response){
           msg.empty();
           msg.append($('<p id="required"></p>').text('Uploaded Photo'));
           console.log('SUCCESS RESPONSE: ', response);
        },
        error: function (xhr, ajaxOptions, thrownError) {
        },
        complete: function(data){
        }
     });
});

然后在路线回叫中:

function upload_employee_photo($request){
    
    $file_params = $request->get_file_params();
    if( isset( $file_params['employeePhoto']['tmp_name'] ) ) {
        $file = file_get_contents( $tmp_name );
        file_put_contents( 'test.jpg', $file );
    }
    //access the data here so i could do something like
    //$location = './img/';  
    //move_uploaded_file($_FILES["employee-photo"]["tmp_name"], $location);
}

$file_params变量将包含执行文件上载过程所需的多部分表单数据。您可以如上所述将tmp_namefile_get_contents()file_put_contents()一起使用。
另外,请查看JS函数中的xhr.setRequestHeader('X-WP-Nonce', localized.nonce);,因为您需要用自己生成的nonce替换localized.nonce

相关问题