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



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

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) {
// ??
},
});
});

谢谢。

经过进一步的研究和试用,我能够找到如何在没有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 (isset($_POST['submit'])) {
/* Get other form data as usual. */
$name = $_POST['name'];

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

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

对于多个图像,JS部分使用HTML/CSS类,PHP部分使用循环。

还有另一个解决方案;

launchUpload(e) {
const that = this;
new Compressor(e.target.files[0], {
quality: 0.6,
maxWidth: 250,
minWidth: 250,
success(compressedResult){
that.init(compressedResult)
},
error(err) {
console.log(err.message);
},
})
}
init(file) {
this.compressed = file;
},

最新更新