0

Note:

The answers & comments below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.

See the answer in this question for details as well as a demo:
How to set file input value programatically (i.e.: when drag-dropping files)?

I'm trying to implement a drag & drop functionality for uploading images with Jquery.

Here is my code:

upload.html

    <form id ="image_upload_form" action="" method="post" enctype="multipart/form-data">

        <input id="id_image" type="file" name="image">
        <input type="submit" value="Upload" />

    </form>

    <div id="drop_field"></div>

image_upload.js

$(document).ready(function() {
    var drop_field = $("#drop_field");
    drop_field.bind('dragover', file_drag_over);
    drop_field.bind('drop', file_select);   
});



function file_select(event) {
    event.stopPropagation();
    event.preventDefault();

    var file = event.originalEvent.dataTransfer.files [0];
    $("#id_image").val(file);
}



function file_drag_over(event) {
    event.stopPropagation();
    event.preventDefault();

    event.originalEvent.dataTransfer.dropEffect = "copy";    
}

Everything works fine except when I drop the image file onto the field, it gives me a security error:

SecurityError: The operation is insecure.
    this.value = val;

I guess this is happening because I'm trying to modify the "value" attribute of a file input field. What is the right way to upload the file without getting this security error?

Thanks!!

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user2492270
  • 2,215
  • 6
  • 40
  • 56

1 Answers1

2

The error is because you are trying to set the value of a file input type, It is not possible to set the value of a file input type because of security reasons.

Also read this question and from MDN

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531