File types restrictions
Due to security reasons it is sometimes necessarry to restrict specific file types when uploading. Following customization in the index.html is showing an example on how to handle the file extensions:
injector.services.files.manager.getAcceptFilter = function(fileChooserName, filter) {
if (fileChooserName === 'uploadFC') {
return "image/png";
}
return filter;
};
injector.services.files.manager.validateUploadedFile = function(file) {
if (file.name.endsWith(".png") || file.type === 'image/png') {
return { valid: true };
}
return { valid: false, error: "Cannot upload file - " + file.name };
};
Drag & Drop
Webswing supports drag & drop functionality between swing components, drag & drop upload to file chooser and direct drag & drop of file from local system to swing component.
File chooser upload
To upload a file using drag & drop to a file chooser, simply open file chooser and drop a file from local file system to the marked area. Note that transparentFileSave
config should be false
.
Direct drag & drop
To use direct drag & drop you first need to register a swing component that should receive the uploaded file. Use WebswingApi
method to do this:
if (WebswingUtil.isWebswing()) {
WebswingApi api = WebswingUtil.getWebswingApi();
api.registerDropComponent(pic1);
}
The registered component must have a valid TransferHandler
:
pic1.setTransferHandler(picHandler);
This is an example of a simple TransferHandler
:
class PictureTransferHandler extends TransferHandler {
private static List<DataFlavor> supportedFlavors = Arrays.asList(DataFlavor.javaFileListFlavor);
public boolean importData(JComponent c, Transferable t) {
if (canImport(c, t.getTransferDataFlavors())) {
if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
try {
List<File> fileList = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList != null && !fileList.isEmpty()) {
File droppedFile = fileList.get(0);
return true;
}
} catch (IOException | UnsupportedFlavorException e) {
// log
}
}
}
return false;
}
public boolean canImport(JComponent c, DataFlavor[] flavors) {
for (int i = 0; i < flavors.length; i++) {
if (supportedFlavors.contains(flavors[i])) {
return true;
}
}
return false;
}
}