11

I am using an input file element to upload file in my JSP page. The user can upload the file by clicking on a button which opens a form with browser's browse button

Now, I want to upload the file by using drag drop feature of HTML5 (as described @ html5 rocks page). I am able to extract the file name using File API. Is there a way to load the input file element with the dropped file using File API? (So that I may use the same behavior to upload file)

user760755
  • 111
  • 1
  • 4

3 Answers3

5

There's no way to set the value of a <input type=file> directly in JS. That action requires user intervention (and a click on a file picker). However, you can use xhr.send(FormData) or xhr.send(File) to send the files. See my response here:

HTML5 File API readAsBinaryString reads files as much larger, different than files on disk

In your drop handler, just pas the FileList obtained from evt.dataTransfer.files to that uploadFiles() helper.

Community
  • 1
  • 1
ebidel
  • 23,921
  • 3
  • 63
  • 76
  • This is the best way to handle drag and drop uploading, bar none. I made a fiddle, based on ebidel's code, to show it in action. http://jsfiddle.net/chad/Qrfb7/ – Chad von Nau Jan 12 '13 at 02:15
2

I was able to set the "files" attribute of the input element with the files property of the dataTransfer object.

document.getElementById("insert input file id").files = evt.dataTransfer.files;

I just tried using getelement.value and it errors. Set the files property with the files list.

Happy Programming!

Kremnari

Kremnari
  • 421
  • 5
  • 7
  • I like this solution. It doesn't work in IE 11 or Firefox though (input.files is a read-only property). – Dave May 11 '15 at 17:28
  • 1
    does it actually submit the file when you post the form? doesn't look like it for me (Chrome v43) – Anentropic May 24 '15 at 22:29
0

it is indeed impossible to handle anything client related in javascript. You could however use the file api to convert the image to base64. You can then send this value to the server through a form and a hidden input value (or one created with javascript), decode it in php or whatever serverside language you're using, and save it as an image file.

dreagan
  • 2,426
  • 6
  • 24
  • 34