Compressor.js-通过常规表单提交上传图像(无Ajax)

问题描述 投票:0回答:1

我在上传之前使用以下脚本在客户端上压缩图像:

https://github.com/fengyuanchen/compressorjs

我可以使用以下代码通过Ajax很好地上传图像:

// Following is a form with #name and #image input fields and #submit button:

var formData = new FormData();

$('#image').change(function(e) {
    var img = e.target.files[0];
    new Compressor(img, {
        quality: 0.8,
        maxWidth: 1600,
        maxHeight: 1600,
        success(result) {
            formData.append('image', result, result.name);
        },
    });
});

$('#submit').click(function() {
    formData.append('name', $('#name').val());

    $.ajax({
        type: 'POST',
        url: 'form-script.php',
        data: formData,
        contentType: false,
        processData: false
    }).done(function() {

    }); 
});

我需要通过常规表单提交方式上传图片-无Ajax-,但我无法做到这一点。我在问以下代码中如何使用result,以便在提交表单时提交压缩图像。附带说明,我使用PHP服务器端。

$('#image').change(function(e) {
    var img = e.target.files[0];
    new Compressor(img, {
        quality: 0.7,
        maxWidth: 1200,
        maxHeight: 1200,
        success(result) {
            // ??
        },
    });
});

谢谢。

javascript image image-compression
1个回答
0
投票

经过进一步的研究和试验,我能够找到使用Ajax来发布压缩图像的方法,方法如下:

表格:

<form id="form" action="" method="post" enctype="multipart/form-data">
    <input type="text" id="name" name="name">
    <input type="file" id="image">
    <!-- A hidden input is needed to put the image data after compression. -->
    <input type="hidden" id="image-temp" name="image">
    <input type="submit" name="submit" value="Submit">
</form>

图像压缩:

$('#image').change(function(e) {
    var img = e.target.files[0];
    new Compressor(img, {
        quality: 0.8,
        maxWidth: 1600,
        maxHeight: 1600,
        success(result) {
            var reader = new FileReader();
            reader.readAsDataURL(result);
            reader.onloadend = function() {
                var base64data = reader.result;
                $('#image-temp').val(base64data);
            }
        },
    });
});

服务器端(PHP):

if (!empty($_POST['image'])) {
    file_put_contents('images/image.jpg', file_get_contents($_POST['image']));
}

根据需要使用想要的目录(images /)和文件名(image.jpg)。

对于多个图像,请为JS部分使用类,为PHP部分使用循环。

© www.soinside.com 2019 - 2024. All rights reserved.