【问题标题】:Javascript resize image when file is selected and upload the new image instead of original选择文件时Javascript调整图像大小并上传新图像而不是原始图像
【发布时间】:2019-03-01 09:27:49
【问题描述】:

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

我猜 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>

【问题讨论】:

    标签: javascript image upload resize


    【解决方案1】:

    您在技术上是正确的,但来自输入的文件是只读。所以浏览器不会让你更改这些文件。您可以做的是创建新的表单数据并在其中附加所有新图像,然后使用 fetch 发送上传以异步发送而不刷新页面。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2016-08-08
        • 2012-05-29
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-10
        相关资源
        最近更新 更多