Skip to content
Advertisement

Upload, resize and send images to server with javascript

After struggling with this issue for 2 days, reading a lot of material online, here I am begging for your help.

I’m trying to resize some images uploaded via FileReader, resize with canvas and send to my server with php.

Everything works as expected, except when I try to upload multiple files. The script loads only the last image, despite showing base64 data for all images with a console.log ();

I’m missing something that I don’t know what it is.

Here is the code:

<input type="file" id="input"  onchange="process()" multiple/>

function process(){

const file = document.querySelector("input").files;    

var abc = [];

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

    if(!file[i]) return;

    const reader = new FileReader();

    reader.readAsDataURL(file[i]);     

    reader.onload = function(event){
        const imgElement = document.createElement("img");
        imgElement.src = event.target.result;

        imgElement.onload = function(e){
            const canvas = document.createElement("canvas");
            const MAX_WIDTH = 800;

            const scaleSize = MAX_WIDTH / e.target.width;
            canvas.width = MAX_WIDTH;
            canvas.height = e.target.height * scaleSize

            const ctx = canvas.getContext("2d");

            ctx.drawImage(e.target, 0,0, canvas.width, canvas.height)

            var srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");

            sendToServer(srcEncoded);

        }
    };        

}

}

function sendToServer(data){
    let formData = new FormData(); 

    formData.append("foto", data);
    fetch('teste.php', {method: "POST", body: formData});

}

As gugateider said, the javascript part its ok.

I think the problem its on the server side. It only saves the last image no mather how much I selecte in the input.

Unfortunately I only have a PHP server, which is enough, but it limits the possibilities of solutions for this technology.

Here is the php code.

$data = $_POST['foto'];
list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents(round(microtime(true)).'_image.png', $data);

Advertisement

Answer

Problem Solved!

I think the round(microtime(true)) wasn’t enough to generate unique names. I changed it to uniqid() and worked.

So the PHP code becomes:

$data = $_POST['foto'];
list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents(uniqid().'_image.png', $data);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement