如何将formData中的裁剪图像发送到PHP

时间:2019-10-15 18:40:56

标签: javascript php html cropperjs

我有一个包含多个输入的表格。一个输入是文件上传器。我正在使用Cropperjs。很好它产生一个base64 img。我希望能够将此裁剪的预览图像传递到php页面,以与其他发布变量一起处理为ajax formData。我可以通过php中的Submit按钮传递其他$ _POST变量。我如何使图像通过?

对我来说,似乎没有追加到formData上,或者我不是在要求正确的FILES var ...

https://jsfiddle.net/nick1572/c6027thL/6/

HTML

<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="modalLabel">Crop the image</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <div class="img-container">
              <img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary" id="crop">Crop</button>
          </div>
        </div>
      </div>
    </div>
 <!--end modal-->

<div class="file_drop_zone">
  <div class="preview">
    <img id="preview_image" accept="image/*"><!-- this is the image that needs to be passed.-->
  </div><!--end preview-->

    <div class="file__controls">
      <label for="file_input">
        <i class="fa fa-upload download_icon"></i><br>
        <span class="drag__files_or">Drag File in or</span>
        <span class="choose__file_btn">Choose File</span>
        <input type="file" name="file" id="file_input">
      </label>
    </div>
</div><!--End file_uploader-->

JS


 // Set the vars

    var drop_zone = document.querySelector('.file_drop_zone');
    var input = document.getElementById('file_input');
    var image = document.getElementById('image');
    var preview_image = document.getElementById('preview_image');
    var preview_wrapper = document.querySelector('.preview');
    var $modal = $('#modal');
    var cropper;
    var $submit = $('.seminar_form_submit');
    var $event_form = $('.seminar_event_form');

    // Create a function to read the file upload
    // provided by the user.

    function readFile(event) {
        var url;
        // File passed to FileList
        var file = event.target;
        // create a variable to pass in the the url.
        // In this case it is the reader result. Then
        // show the bootstrap modal.
        var done =  function (url) {
            input.value = '';
            image.src = url;
            $modal.modal('show');
        };

        // Create a new File Reader instance
        // for getting the result

        var reader = new FileReader();
        reader.onload = function() {
            done(reader.result);
        };

        // If the event type is a 'change' then grab the
        // file otherwise if the file is a 'drop'
        // we get the file through the dataTransfer

        if (event.type === 'change') {
            reader.readAsDataURL(file.files[0]);
            console.log(file.files[0]);

        } else if (event.type === 'drop') {
            reader.readAsDataURL(event.dataTransfer.files[0]);
        }
    }

    // Once the modal is shown, create a new cropper instance and
    // assign it to the #image div. // Once the modal is hidden
    // destroy the instance for resetting cropper.

    $modal.on('shown.bs.modal', function () {

        /* global Cropper */

        cropper = new Cropper(image, {
            aspectRatio: 1,
            viewMode: 0,
            zoomable: true,
            cropBoxMovable: true,
            minContainerWidth: 100,
            minContainerHeight: 100,
            autoCropArea: 0.5
        });
    }).on('hidden.bs.modal', function () {
        cropper.destroy();
        cropper = null;
    });

    // Add listener to the crop button on the modal. If there is a cropper
    // instance then set the canvas to the getCroppedCanvas function
    // provided by cropperjs. We can set the dims there. We want to set the initial
    // preview image src to the canvas. This is now a string in the form of
    // a base64. Then hide the modal.

    var crop = document.getElementById('crop');
    var canvas;
    var initialPreviewURL;


    crop.addEventListener('click', function (crop) {
        canvas = cropper.getCroppedCanvas({
            width: 180,
            height: 180,
            fillColor: '#fff',
            imageSmoothingEnabled: false,
            imageSmoothingQuality: 'high'
        });
        initialPreviewURL = preview_image.src;
        preview_image.src = canvas.toDataURL();
        preview_wrapper.style.display = 'block';
        $modal.modal('hide');
    }); 


    $event_form.on('submit', function(e) {
        e.stopPropagation();
        e.preventDefault();
        var form_data = new FormData(document.getElementById('my_form'));

        canvas.toBlob(function(blob) {
            form_data.append('preview_image', blob);
            for (var key of form_data.entries()) {
                console.log(key); 
             }
        });


        $.ajax({
            url: 'create_event.php',
            data: form_data,
            cache: false,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function() {
                console.log('success');
            },

            error: function () {
                preview_image.src = initialPreviewURL;

            },
            complete: function () {
                console.log('completed');
            }
        });

    });


我能够在控制台中看到输出。通过在条目上使用for循环

["preview_image", File]

如果我在php上error_log。输出仅显示“此处错误”,不显示预览图像

error_log("error here");
error_log($_FILES['preview_image']);

这是php页面上“网络”>“响应”选项卡的输出。

var_dump($ _ POST);或var_dump($ _ FILES);


array(9) {
  ["subject"]=>
  string(12) "Persons Name"
  ["details"]=>
  string(39) "Designer and wanna be web developer...."
  ["event-title"]=>
  string(21) "This is another title"
  ["location"]=>
  string(58) "This place"
  ["aux"]=>
  string(13) "George Carlin"
  ["start-date"]=>
  string(10) "2019-10-18"
  ["start-time"]=>
  string(5) "08:00"
  ["end-date"]=>
  string(10) "2019-10-18"
  ["end-time"]=>
  string(5) "09:00"
}



array(1) {
  ["file"]=>
  array(5) {
    ["name"]=>
    string(0) ""
    ["type"]=>
    string(0) ""
    ["tmp_name"]=>
    string(0) ""
    ["error"]=>
    int(4)
    ["size"]=>
    int(0)
  }

谢谢!

1 个答案:

答案 0 :(得分:0)

好几天后,我只添加了一个隐藏字段并将该值设置为base64字符串。我已经有大量的PHP错误处理脚本,因此我删除了ajax调用。现在,base64字符串与POST数组一起传递。

相关问题