Wicket file upload example

Example to show you how to create a Wicket FileUploadField component, to let user select a file from local drive and upload to the server.


//Java
import org.apache.wicket.markup.html.form.upload.FileUploadField;

	form.setMultiPart(true);
	form.add(fileUpload = new FileUploadField("fileUpload"));
							
//HTML
<input wicket:id="fileUpload" type="file"/>

To upload file, you have to enable “multipart mode” in the Wicket form component.

1. FileUpload example

Example to render a fileupload component, and limit the uploaded file size to 10k. And the new uploaded file will be saved into a predefined location.


package com.mkyong.user;

import java.io.File;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.util.lang.Bytes;

public class FileUploadPage extends WebPage {

	private FileUploadField fileUpload;
	private String UPLOAD_FOLDER = "C:\\";

	public FileUploadPage(final PageParameters parameters) {

		add(new FeedbackPanel("feedback"));

		Form<?> form = new Form<Void>("form") {
		 @Override
		 protected void onSubmit() {

			final FileUpload uploadedFile = fileUpload.getFileUpload();
			if (uploadedFile != null) {

				// write to a new file
				File newFile = new File(UPLOAD_FOLDER
					+ uploadedFile.getClientFileName());

				if (newFile.exists()) {
					newFile.delete();
				}

				try {
					newFile.createNewFile();
					uploadedFile.writeTo(newFile);

					info("saved file: " + uploadedFile.getClientFileName());
				} catch (Exception e) {
					throw new IllegalStateException("Error");
				}
			 }

			}

		};

		// Enable multipart mode (need for uploads file)
		form.setMultiPart(true);

		// max upload size, 10k
		form.setMaxSize(Bytes.kilobytes(10));

		form.add(fileUpload = new FileUploadField("fileUpload"));

		add(form);

	}
}

2. HTML page

Render the component via HTML input tag.


<html>
<head>
<style>
.feedbackPanelINFO {
	color: green;
}
.feedbackPanelERROR {
	color: red;
}
</style>
</head>
<body>
	<h1>Wicket file upload example</h1>

	<div wicket:id="feedback"></div>
	<form wicket:id="form">
		<p>
			<label>Select file :</label> 
			<input wicket:id="fileUpload" size="40" type="file"/>
			<input type="submit" value="Upload"/>
		</p>
	</form>
		
</body>
</html>

3. Demo

Start and visit – http://localhost:8080/WicketExamples/

If file size is more than 10k, display error

wicket file upload error

Everything ok, display saved file name.

wicket file upload
Download it – Wicket-FileUpload-Example.zip (7KB)

References

  1. Wicket FileUpload Javadoc
  2. Wicket FileUploadField Javadoc

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
11 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
12 Comment authors
ShreyasLuisRajesh JsaniduQurbonov Recent comment authors
newest oldest most voted
Shreyas
Guest
Shreyas

Can you show us how to display the contents of the uploaded file from the above process?

Luis
Guest
Luis

Dear yong mook kim, I am having problems with my file Upload form in wicket. I am not being able of uploading any file into the online server. This script worked already, but for some time it stopped. So I search for answers, but I was getting the same error. My code is equal to yours. The difference is the folder path: String UPLOAD_FOLDER = “https://project11.myserver.com/content/images/”; Could you help with this problem? Thank you in advance Luis P.S.: The explanation is under Server: Operating System: Debian GNU/Linux 7 (wheezy) Tomcat: Tomcat 7 Permissions in folder /content/images/: 777 Local: Tomcat: Tomcat… Read more »

Rajesh J
Guest
Rajesh J

Hi Mk Yong!,

I always prefer your examples while implementing any Java stuff because they are simple and “They WORK!”. Thanks a lot!

My current requirement is to Upload and parse a .xls or .xlsx file (client may upload any of the formats) and persist various fields in the file (columns) to Database tables.

I haven’t yet found a concrete pure servlet (+ POI) solution that does just that yet. So I was wondering whether you already have any such example at your disposal.

Regards,
Rajesh J

sanidu
Guest
sanidu

Thanks for your example, but I’ve got an exception and handled it as below.

 uploadedFile.writeTo(newFile); 

After this line , put

 uploadedFile.closeStreams();

otherwise exception occurs.

Qurbonov
Guest
Qurbonov

I Have Errorrrrrrrrrrr

Last cause: ErrorAccess is denied
WicketMessage: Method onFormSubmitted of interface org.apache.wicket.markup.html.form.IFormSubmitListener targeted at [ [Component id = form]] on component [ [Component id = form]] threw an exception

Sue
Guest
Sue

Ich möchte die maximale Grenze für die hochzuladene Datei ändern. Geht das mit dem Beispiel? Und wo kann ich die Fehlerausschrift entsprechend anpassen?

Javier
Guest
Javier

Hi! Im im trying to get and web app working wich lets the user upload a file and then the web app can display the image uploaded, i can get the file uploaded, to UPLOAD_FOLDER =”..\uploads\”, but im finding problems when i try to display since if i use the same directory structure LIKE :

“..\uploads\” + FILE_NAME

it goes to another folder!

Has anyone tryied this before?

Thanks!!!!

ash
Guest
ash

how do i upload a image directly in my inbox and view it there only..
please help asap.i have created a inbox page under my login app. i want to allow the user to upload and view it.how can i do that?

mike
Guest
mike

How this uploaded file can be received by a servlet called myServlet which extends HttpServlet that is like :->

public class myServlet extends HttpServlet { }

and which is using apache commons file uploads as follows:

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

Also would be great if your client program should be able to do file chunking to upload a big file.

Rich
Guest
Rich

Mkyong you rock! After google searching for clear, concise examples of code that fulfills a business requirement and is needed *quickly* your thoughtful, careful layout filled the need. Other search results went too deep into the Joy of Wicket and its coolness, etc. which is fine, but sometimes a geek just needs a solution.

-Rich

GeppyZ
Guest
GeppyZ

if you want to add your own custom feedback message add this to the properties file of your page:

 
form.uploadTooLarge=The file is too large: ${maxSize}