-1

Can I somehow choose and upload a local image file from the file dialog via Javascript (I'm trying to use UserScript to do it)?

I can open the file dialog via the following code:

function performClick(node) {
   var evt = document.createEvent("MouseEvents")
   evt.initEvent("click", true, false)
   node.dispatchEvent(evt)
}

performClick(document.getElementById('fld_images'))

But what about uploading? Is it possible? Maybe HTML5?

Thanks in advance.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

0

You need to use a file input, then once you have the file handle you can use the fileReader to access the file. JavaScript cannot directly select files from the user's drive due to security.

<input type="file" id="fileInput" />


$('#fileInput').on('change', function() {
    alert(this.files)
})

this.file[0] will be your first file.

See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_forms_through_JavaScript#Dealing_with_binary_data

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • 1
    You can only get the file handle from the change event. The change event will only fire if the user clicks on the fields. The question is about triggering the click event http://jsfiddle.net/DSARd/965/ – Ruan Mendes May 15 '14 at 20:13
0

If your file field is visible, your code should work. It probably doesn't work because you've made your file field invisible. Credit to https://stackoverflow.com/users/56449/adardesign with the answer at https://stackoverflow.com/a/7302101/227299

Try setting the upload field to be position:absolute; top:-100px http://jsfiddle.net/DSARd/967/

HTML

<input type="file" id="fld_images">
<button id="button">Upload</button>

JS

function performClick(node) {
   var evt = document.createEvent("MouseEvents");
   evt.initEvent("click", true, false);
   node.dispatchEvent(evt, true);
}
document.getElementById('button').addEventListener('click', function(){
    performClick(document.getElementById('fld_images'));
});

CSS

#fld_images{ position:absolute; top:-100px; }
Community
  • 1
  • 1
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217