使用javascript将裁剪的图像发送到我的服务器时出现问题

时间:2019-01-28 15:49:07

标签: javascript ruby-on-rails ruby

我是裁剪图像的新手,在保存裁剪后的图像时遇到了一些问题。我的代码已经上传了新图像,并显示了预览裁剪的图像,但是我被此步骤卡住了。

我有一个已经尝试过的代码,当图像来自输入div时,该图像将图像发送到服务器,并且该元素是一个对象htmlinputelement。当我尝试发送预览图片时,它是一个对象,无法正常工作。我看到我必须将对象转换为文件,但是我不知道这是否是正确的方法,而且我的JavaScript技能也不是很好。

//此代码是要发送到服务器并且可以正常工作 函数uploadpicture(input){

if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
        $('#img_final')
        .attr('src', e.target.result);
    };

    reader.readAsDataURL(input.files[0]);

    //enviar img via ajax
    var file_data = input.files[0];

    var form_data = new FormData();

    var cpf_can = '<%= @candidato.cpf %>';
    console.log('cpf: ', cpf_can);

    form_data.append("file", file_data);
    form_data.append("cpf", cpf_can);


    var request = new XMLHttpRequest();
    request.open('POST', '/changecurimg/envia3por4ajax', /* async = */ false);
    request.send(form_data);

    if (request.response == 500){
        alert("Erro ao inserir foto! tente novamente");
        location.reload();
        $("#myModal").modal('hide');
    }
    else if (request.response == 200){
        location.reload();
        $("#myModal").modal('hide');
        $('#img_final').removeClass('hidden');
        $('#img_prev').addClass( "hidden" );
    }
}

}

//此代码显示裁剪和预览图像 函数resize_modal(){

var $image = $(".img-container > img"),
    $dataX = $("#dataX"),
    $dataY = $("#dataY"),
    $dataHeight = $("#dataHeight"),
    $dataWidth = $("#dataWidth");

$image.cropper({
  aspectRatio: 3 / 4,
  data: {
    x: 480,
    y: 60,
    width: 640,
    height: 360
  },
  modal: true,
  preview: ".img-preview",
  done: function(data) {
    $dataX.val(Math.round(data.x));
    $dataY.val(Math.round(data.y));
    $dataHeight.val(Math.round(data.height));
    $dataWidth.val(Math.round(data.width));
  }
});

var $inputImage = $("#inputImage");
if (window.FileReader) {
    $inputImage.change(function () {
        var fileReader = new FileReader(),
                files = this.files,
                file;

        if (!files.length) {
            return;
        }

        file = files[0];

        if (/^image\/\w+$/.test(file.type)) {
            fileReader.readAsDataURL(file);
            fileReader.onload = function () {
                $inputImage.val("");
                $image.cropper("reset", true).cropper("replace", this.result);
            };
        } else {
            showMessage("Please choose an image file.");
        }
    });
} else {
    $inputImage.addClass("hide");
};

// $('document').ready(function(){
//     $('#myModal0').modal('show');
// };

};

0 个答案:

没有答案