使用 Javascript (jQuery) 上传多个调整大小的图像

Upload Multiple Resized Images Using Javascript (jQuery)

我将不同来源的代码放在一起,如果我删除调整大小的代码,它就可以工作。我可以按原样使用 for 循环上传多个文件,但无法掌握调整大小的技术。我怀疑文件 reader 有问题。如何修复调整大小的部分?谢谢

这是 JavaScript 部分:

function fileToDataUri(field) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => {
      resolve(reader.result);
    });
    reader.readAsDataURL(field);
  });
}       

function resizeImage(imgToResize, resizingFactor = 0.3) {
  const canvas = document.createElement("canvas");
  const context = canvas.getContext("2d");
  const originalWidth = imgToResize.width;
  const originalHeight = imgToResize.height;
  const canvasWidth = originalWidth * resizingFactor;
  const canvasHeight = originalHeight * resizingFactor;
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  context.drawImage(imgToResize, 0, 0, originalWidth * resizingFactor, originalHeight * resizingFactor );
  return canvas.toDataURL();
}

function uploadImage() {

    var input_files = document.getElementById('input_images');
    var form = new FormData();

    for (i = 0; i < input_files.files.length; i++) {

        // RESIZE
        var file = input_files.files[i];

        var original_image = new Image();
        original_image.src = fileToDataUri(file);

        var resized_image = new Image();
        resized_image.src = resizeImage(original_image);

        // UPLOAD 
        form.append("image", resized_image);

        var settings = {
            "url": "my-api-url",
            "method": "POST",
            "timeout": 0,
            "processData": false,
            "mimeType": "multipart/form-data",
            "contentType": false,
            "data": form
        };

        $.ajax(settings).done(function (response) {
            //console.log(response);
            var jx = JSON.parse(response);
            console.log(jx.data.url);
            document.getElementById("uploaded_images").innerHTML = document.getElementById("uploaded_images").innerHTML + "<br><div><img src='" + jx.data.url + "'> &nbsp; " + jx.data.url + "</div>";
        });

    }
}

HTML部分:

<input type="file" accept="image/*" name="input_images" id="input_images" multiple> 
<input type="button" value="Upload" onclick="uploadImage();">
<div id="uploaded_images"></div>

这个对我来说很好用。所有内容都已从 jQuery 转换为 JavaScript。

<!doctype html>
<html>
<head>
    <title>Upload Images</title>
    <meta charset="utf-8">
    <style>
        .uploaded {
            border:1px solid #CCC;
            margin:5px;
        }
    </style>
    <script>

    function getFilesReady(e) {
        var preview_images = document.getElementById("preview_images");
        if (e.target.files) {
            var filesAmount = e.target.files.length;
            for (i = 0; i < filesAmount; i++) {
                var reader = new FileReader();
                reader.onload = function(event) {
                    let html = document.querySelector("body").innerHTML;
                    let doc = new DOMParser().parseFromString(html, "text/html");
                    let images = doc.querySelectorAll("img");
                    let image = images[images.length-1];
                    image.setAttribute("src", event.target.result);
                    preview_images.appendChild(image);
                }
                reader.readAsDataURL(e.target.files[i]);
            }
        }
    }
     
    function getResizedBlob(e,file) {
        var img = document.createElement("img");
        img.src = e.target.result;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        var MAX_WIDTH = 1000;
        var MAX_HEIGHT = 1000;
        var width = img.width;
        var 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;
            }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        var dataurl = canvas.toDataURL(file.type);
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type:mime});
    }
    
    
    var upload_counter = 0;
    var total_files;
    function multipleImageUpload() {
        document.getElementById("image_loader").innerHTML = "<img src='https://i.ibb.co/NsY3nDw/loader-on.gif'>";
        var files_to_upload = document.getElementById('selected_files').files;
        total_files = files_to_upload.length;
        for (i = 0; i < total_files; i++) {
            var file = files_to_upload[i];
            //console.log(file);
            var reader = new FileReader();
            reader.onload = async function(e) {
                const form = new FormData();
                form.append("image", getResizedBlob(e,file));
                try {
                    const response = await fetch('imgbb-api-url',{
                        method:'POST',
                        body:form
                    });
                    const result = await response.json();
                    upload_counter++;
                    var uploaded_images = document.getElementById("uploaded_images");
                    uploaded_images.innerHTML = uploaded_images.innerHTML + "<a target='_blank' href='" + result.data.url + "'><img src='" + result.data.thumb.url + "' class='uploaded'></a>";
                    console.log(upload_counter + " ---- " + result.data.url);
                    
                } catch(e) {
                    console.log(e);
                }
            }
            reader.readAsDataURL(file);
        }
        
        // keep checking after 2 seconds to see if all the files are uploaded
        timer = setInterval(function() {
            if (upload_counter == total_files) {
                console.log("last message after all the uploads");
                document.getElementById("image_loader").innerHTML = "";
                document.getElementById("selected_files").value = "";
                clearInterval(timer);
            }
        }, 2000);
    }
    </script>
</head>
<body>
    <div>
        <input id="selected_files" name="selected_files" type="file" class="selected_files" accept="image/*" onchange="getFilesReady(event);" multiple><br>
        <br>
        <input type="button" value="Upload"  onclick="multipleImageUpload()"> 
        <span id="image_loader"></span>
    </div>
    <form method="post">
        <div id="uploaded_images"></div>
    </form>
    
    <div id="preview_images" style="display:none;"><img src="https://i.ibb.co/64DYhjZ/dummy.gif"></div> 
</body>
</html>