0

I'm working on this classical feature: choose a file in the browser ("Browse"), let JavaScript resize it (max width / height = 500 pixels) and upload it to server, and then let PHP save it to disk.

Here is what I currently have (based on this other question)

$("#fileupload").change(function(event) { 
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.onload = function (readerEvent) {
        var image = new Image();
        image.onload = function (imageEvent) {
            var canvas = document.createElement('canvas'), max_size = 500, width = image.width, height = image.height;
            if (width > height) { if (width > max_size) { height *= max_size / width; width = max_size; } } 
            else { if (height > max_size) { width *= max_size / height; height = max_size; } }
            canvas.width = width;
            canvas.height = height;
            canvas.getContext('2d').drawImage(image, 0, 0, width, height);
            var dataUrl = canvas.toDataURL('image/jpeg');
            var resizedImage = dataURLToBlob(dataUrl);
            $.ajax({type: "POST", url: "index.php", success: function(data, status) { }, data: { content: resizedImage, filename: ?? }});
        }
        image.src = readerEvent.target.result;
    }
    reader.readAsDataURL(file);
}

var dataURLToBlob = function(dataURL) {
    var BASE64_MARKER = ';base64,';
    if (dataURL.indexOf(BASE64_MARKER) == -1) { var parts = dataURL.split(','); var contentType = parts[0].split(':')[1]; var raw = parts[1]; return new Blob([raw], {type: contentType}); }
    var parts = dataURL.split(BASE64_MARKER);
    var contentType = parts[0].split(':')[1];
    var raw = window.atob(parts[1]);
    var rawLength = raw.length;
    var uInt8Array = new Uint8Array(rawLength);
    for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); }
    return new Blob([uInt8Array], {type: contentType});
}
<input id="fileupload" type="file">

The PHP part would be:

<?php
if (isset($_POST['content'])) file_put_contents($_POST['filename'], $_POST['content']);
?>

This currently doesn't work, how should I do the AJAX part to make it work (how to send the data + filename)? Should a FormData be used, if so why and how?

Community
  • 1
  • 1
Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

0

You need to use $_FILES array to retrieve the image info:

if (is_uploaded_file($_FILES['new_img']['tmp_name'])) {
    $newimg = $_FILES['new_img']['name'];
    move_uploaded_file($_FILES['new_img']['tmp_name'], "../images/{$newimg}");
}

file_put_contents is a function to write files. When you upload a file it is stored in a temp dir, so you can check with is_uploaded_file that it is uploaded with the $_FILES['new_img']['tmp_name'].

You can use it's original name with $_FILES['new_img']['name'] or rename it to prevent injections. Then you have to move the image to it's final location with move_uploaded_file.

I almost forgot the form:

<form action="yourpage.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="new_img" id="new_img">
    <input type="submit" value="Upload Image" name="submit">
</form>
MarioZ
  • 981
  • 7
  • 16
  • Thanks. I also have this `formData.append('data', resizedImage);` => `TypeError: Not enough arguments to FormData.append.`. If I console.log resizedImage, I get `Blob { size: 58596, type: "image/jpeg" }`. Why can't I append this to formData ? – Basj Jan 18 '17 at 00:00