Javascript 选择文件后调整图像大小并上传新图像而不是原始图像

Javascript resize image when file is selected and upload the new image instead of original

我正在尝试调整已上传图片的大小,然后再上传新图片。我的代码运行没有错误,我可以看到图像已成功调整大小,但不知何故上传的是原始图像而不是新创建的图像。

我猜 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 发送上传它以异步发送它而不刷新页面。

Resize image in the client side before upload 找到了答案。文件输入的文件列表可以用 fileInput.files = fileList

改变