File Upload and Download

AjaxSwing supports file upload and download through JFileChooser dialog.

File Upload

JFileChooser of type OPEN_DIALOG is rendered as file upload in the browser. If a component such as JButton displays JFileChooser, a uniform file upload dialog is shown in the browser where a user can select a file to be uploaded and then submit the page. Here is an example of file upload to get image from user and display in a JLabel:

JButton btOpen = new JButton("Open");
btOpen.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser();
		if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(null)) {
			label.setIcon(new ImageIcon(chooser.getSelectedFile().getAbsolutePath()));
		}
	}
});

File Download

JFileChooser of type SAVE_DIALOG is rendered as file download. AjaxSwing detects when Swing application displays that dialog, which point it automatically closes it and streams download to the browser. No custom application code is required. Here is an example of file download to send generated report to user:

JButton btSave = new JButton("Save");
btSave.addActionListener(new ActionListener() {
	public void actionPerformed(ActionEvent e) {
		JFileChooser chooser = new JFileChooser();
		chooser.setSelectedFile(new File("report.png")); // user will see this name during download
		if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(null)) {
			RenderedImage rendered = createReportAsPng();
			ImageIO.write(rendered, "png", chooser.getSelectedFile());			
		}
	}
});