Reputation: 2592
I am using file uploading in my web application by using the <input type="file" />
html tag. My feature works well with choosing a file from the file chooser and submitting the file, however now I want to upload a file on drag and drop events i.e. the user drags a file from some location on his computer and when he drops it in a particular section in my web page, the file starts uploading.
Until now I managed to read the files from the drop event by
function drop(evt)
{
evt.stopPropogation();
evt.preventDefault();
if (containsFiles(evt))
{
var files = evt.dataTransfer.files;
var count = files.length;
// Only call the handler if 1 or more files was dropped.
if (count > 0)
// upload files
}
}
}
but how can I upload these files? I can't change the value of input type = file for security reasons. So what can I do to pass these files to my servlet?
Upvotes: 9
Views: 3869
Reputation: 2249
I believe you want something in the likes to Dropzone.js
I haven't tried it yet, but it's a library that allows for easy drag-and-drop of files to a website that is running it, v3.0 comes without the need to use jQuery.
Upvotes: -2
Reputation: 23047
You have to use FormData (beware of IE support).
When drop happens you need to create FormData object, and append data into it, then POST that form to your url. It is asynchronous method and will not reload your page.
function drop(evt) {
evt.stopPropogation();
evt.preventDefault();
var files = evt.dataTransfer.files;
if (files.length > 0) {
var form = new FormData();
for(var i = 0; i < files.length; ++i) {
var file = evt.dataTransfer.files[i];
form.append('image_' + i, file, file.name);
}
var req = new XMLHttpRequest();
req.open('POST', '/pathToPostData', true);
req.onload = function(evt) {
console.log(req.responseText);
}
req.send(form);
}
}
Beware that I've tested it only in Chrome and Firefox, IE9 probably will not work but IE10 should, if you test it, let us know please.
Upvotes: 3