[英]Compressor.js - Upload image via normal form submission (no 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() {
});
});
我需要通过正常的表单提交-no Ajax-上传图像,但我无法做到。 我在问如何在以下代码中使用结果,以便在提交表单时提交压缩图像。 作为旁注,我使用 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;
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.