I try to make a very simple GWT-Application: The User can choose a txt file an upload it to the Server. Later I want to implement more functionality but for now I'm stuck on the FileUpload:
On the client Side I have the following Code working:
public class GwtDemoProject implements EntryPoint {
private static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL() + "upload";
private FormPanel form;
private Label info;
private FileUpload fileupload;
private Button uploadFileBtn;
public void onModuleLoad() {
init();
uploadFileBtn.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String filename = fileupload.getFilename();
if(filename.length() == 0) {
Window.alert("File Upload failed");
} else if(filename.endsWith(".txt")) {
form.submit();
} else {
Window.alert("File is not a txt-file");
}
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
if(event.getResults().length() == 0) {
} else {
Window.alert(event.getResults());
}
}
});
VerticalPanel vp = new VerticalPanel();
vp.add(info);
vp.add(fileupload);
vp.add(new HTML("<br>"));
vp.add(uploadFileBtn);
form.add(vp);
RootPanel rp = RootPanel.get();
rp.add(form);
}
private void init() {
form = new FormPanel();
form.setAction(UPLOAD_ACTION_URL);
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
info = new Label("Wähle eine Textdatei aus");
fileupload = new FileUpload();
uploadFileBtn = new Button("Upload File");
}
}
On my server side I made the following:
public class FileUploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
File uploadedFile = new File("C:\\samplePath\\"+item.getName()+".txt");
item.write(uploadedFile);
}
} catch (Exception exc) {
}
}
}
In the web.xml I added the following to the Servlets:
<!-- Servlets -->
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>de.gwt.demo.server.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/gwtdemoproject/upload</url-pattern>
</servlet-mapping>
I get no error message but I found out that the List in the Servlet is empty so the while loop is never executed. Is something wrong with the request or the submit?