我正在尝试使用Javascript调整用户输入的大小。我能够接近最后一部分。
以下是我收到的错误消息
下面是代码
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
const file_input = document.getElementById('main_image');
file_input.addEventListener('change', function (e) {
const file = file_input.files[0];
const reader = new FileReader();
reader.onload = function () {
if (!file.name.match(/.(jpg|jpeg|png|gif)$/i)){
alert('Only jpg, jpeg, png, gif accepted at the moment');
file_input.value = "";
}
if (file.size <= (1024*1024)){
const img = new Image();
img.src = reader.result;
console.log("Small Image Width " + img.width);
console.log( "Small Image Height " + img.height);
const preview_image = document.getElementById("preview");
preview_image.src = img.src;
console.log("Thumbnail Image height " + preview_image.height);
console.log("Thumbnail Image width " + preview_image.width);
}
else {
const img = new Image();
img.src = reader.result;
const preview_image = document.getElementById("preview");
const MAX_WIDTH = 1024;
const MAX_HEIGHT = 1024;
img.onload = function(){
console.log(img.width);
console.log(img.height);
let width = img.width;
let height = img.height;
if (width > height){
if (width > MAX_WIDTH){
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
}else {
if (height > MAX_HEIGHT){
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT
}
}
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(img, 0, 0, width, height);
const new_image = document.getElementById("new_image");
new_image.src = canvas.toDataURL('image/jpeg');
new_image.onload = function(){
console.log(this.width);
console.log(this.height);
};
preview_image.src = new_image.src;
file_input.value = new_image.src;
};
如果您想要的是在客户提交表单时将图像发送回服务器,则始终可以将数据转换为base64并将其粘贴到隐藏的<input>
或<textarea>
中。
然后,如果您认为在表单中具有此类按钮很重要,则可以始终使用看起来像“浏览”按钮的按钮。
此外,您可以使用jQuery.ajax()
或fetch()
将base64
或其他类型的数据发送到您的服务器。
我认为最后一行应该是
file_input.src
而不是file_input.value