0

I am trying to replace the uploaded by user image with a smaller one, just before upload.

The concept is to modify the 'src' attribute of the input field with the new resized image src. However, this does not happen. Browser submits the original image.

This is my code:

<input type="file" id="input-file-a" name="image" accept="image/*"/>
<img id="preview"/>


var fileReader = new FileReader();
var filterType = /^(?:image...

fileReader.onload = function (event) {
    var image = new Image();
    image.src = event.target.result;
    var elem_id = 'input-file-a';
    image.onload = function () {
        var canvas = document.createElement("canvas");
        var context = canvas.getContext("2d");
        canvas.width = image.width / 4;
        canvas.height = image.height / 4;
        context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
        document.getElementById('preview').src = canvas.toDataURL();  // <--- This shows the resized preview as expected!
        document.getElementById(elem_id).src = canvas.toDataURL();  // <--- this does not work, should it?       
    };
};

function resizeImage() {
    var elem_id = 'input-file-a';
    var uploadImage = document.getElementById(elem_id);
    if (uploadImage.files.length === 0) {
        return;
    }
    var uploadFile = document.getElementById(elem_id).files[0];
    if (!filterType.test(uploadFile.type)) {
        alert("Please select a valid image.");
        return;
    }

    fileReader.readAsDataURL(uploadFile);
}

What am I doing wrong?

xpanta
  • 8,124
  • 15
  • 60
  • 104

1 Answers1

1

The short answer is You can't. The only way set the value of a file input is by the user select a file. Imagine if someone writes a JS file which sets file input value into some sensitive data (some files from clients computer). This is done for security reasons.

ugursogukpinar
  • 327
  • 1
  • 5
  • Thanks. Is there another way to upload the resized image to the server? E.g. using another input field? or an Ajax request? I have the resized image displayed. There must be a way for sending it to the server, and not sending the original image. – xpanta Jun 15 '18 at 04:32
  • 1
    You can make an ajax request and attach base64 encoded image. Please check here: https://stackoverflow.com/questions/13198131/how-to-save-an-html5-canvas-as-an-image-on-a-server Please let me know if it works. – ugursogukpinar Jun 15 '18 at 10:01