我正在尝试调整上传图像的大小,然后上传新图像。我的代码运行没有错误,我可以看到图像已成功调整大小,但不知何故上传的是原始图像而不是新创建的图像。
我猜测 e.target.files[0] = newimg;不是将上传的图像文件更改为新图像文件的正确方法。正确的做法应该是什么?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ResizeImg(e)
{
const file = e.target.files[0];
const fileName = file.name;
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = event =>
{
const img = new Image();
img.src = event.target.result;
img.onload = () =>
{
const elem = document.createElement('canvas');
const ctx = elem.getContext('2d');
const maxWidth = 50;
const maxHeight = 50;
const ratio = Math.min(maxWidth / img.width, maxHeight / img.height);
const width = img.width * ratio + .5 | 0;
const height = img.height * ratio + .5 | 0;
elem.width = width;
elem.height = height;
ctx.drawImage(img, 0, 0, width, height);
ctx.canvas.toBlob((blob) =>
{
const newimg = new File([blob], fileName, file);
e.target.files[0] = newimg;
});
}
};
}
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input name="infile" type="file" onchange="ResizeImg(this)">
<br><br><input type="submit" name="submit">
</form>
</body>
</html>
最佳答案
您的做法在技术上是正确的,但输入的文件是只读。所以浏览器不会让你更改这些文件。您可以做的是创建新的表单数据并在其中附加所有新图像,然后使用 fetch 发送上传以异步发送而不刷新页面。
关于选择文件时Javascript调整图像大小并上传新图像而不是原始图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941584/