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?
Fortunately, you can easily fix it without having to restart your computer or configure your system settings. In File Explorer, click any file or folder and hold the left button on your mouse. Then, press the Esc key. Now, try dragging and dropping again.
When dropping files into drop zone you get a dataTransfer. files object, that is a FileList type of object, that contains all the files you dragged. Meanwhile, <input type="file" /> element has the property files , that is the same FileList type object. So, you can simply assign the dataTransfer.
To upload data to a server, the client again initiates a connection to the server and then typically sends a HTTP POST request which contains the data to be uploaded. The server knows how to handle such a request and stores the data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With