I needed to make a way for a person to drag a file off of the desktop and onto the browser using a java Applet. And this is the code to make that happen:
public class SomeApplet extends JApplet implements DropTargetListener {
The first step is to implement the DropTargetListener as you extend JApplet (or Applet). This is going to provide the applet the ability to contain a Drop Target. That is right, I said “contain”. I have tried this attaching the Drop Target Listener to the Applet itself unsuccessfully however; it attaches fine to a JPanel or even a Label.
JPanel jp1 = new JPanel();
DropTarget dt2 = new DropTarget(jp1, this);
jp1.setDropTarget(dt2);
Next declare the panel and a Drop Target then attach the drop target to the panel (once again this could be done with a label or whatever).
public void drop(DropTargetDropEvent dtde) {
int action = dtde.getDropAction();
dtde.acceptDrop(action);
fromTransferable(dtde.getTransferable());
dtde.dropComplete(true);
}
First you get the Drop Action from the dtde object which represents the Drop Target Event then accept the Drop using the acceptDrop function. This registers the accepted drop with the applet. Once you accept then you dispatch the function which handles the drop (uploading the file in our case) then tell the applet the drop is complete using the dropComplete function. This is a great place for error handling to return false if there is an error or true if the drop function was successful. Both will have different display consequences which can be seen through testing
Object data = t.getTransferData(DataFlavor.javaFileListFlavor);
java.util.List<File> fileList = (java.util.List<File>) data;
for (File file : fileList) {
if (!is_in_list(file_names, file.getAbsolutePath()) && !file.isDirectory()) {
Lastly we cycle through the list of files we got and decide whether to save them or what to do.
And there you have it: a medium level overview on how to drop a file into the browser on an applet and have it upload.