PDA

View Full Version : File Uploading



Kris Sony
22 Jun 2011, 8:02 AM
Hi

I know there are other posts on this but I just can't get this working. Any clues?

The problem seem is this is false
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

Its like the encoding is not multipart


FormPanel


FormPanel formPanel = new FormPanel();
formPanel.setHeading(TITLE);
formPanel.setFrame(true);
formPanel.setWidth(350);
formPanel.setEncoding(Encoding.MULTIPART);
formPanel.setMethod(Method.POST);
formPanel.setAction(GWT.getModuleBaseURL()+"upgradePackageServlet ");


fileUpload = new FileUploadField();
fileUpload.setName("Select upgrade package");
fileUpload.setAllowBlank(false);


formPanel.add(fileUpload);


Button uploadButton = new Button("Upload");
uploadButton.addClickHandler(new UploadFileClickHandler());
formPanel.add(uploadButton);


UploadFileClickHandler


private class UploadFileClickHandler implements ClickHandler {

@Override
public void onClick(ClickEvent event) {
final String fileName = fileUpload.getValue();

if (fileName.isEmpty()) {
Window.alert("Select a file");
} else {
upgradePackageService.addPackage(fileName, new AsyncCallback<Void>() {

@Override
public void onSuccess(Void result) {
Window.alert("Hunky Dorey " + fileName);

}

@Override
public void onFailure(Throwable t) {
Window.alert("Error uploading file " + t);

}
});
}
}
}





public class UpgradePackageProxyServiceImpl extends RemoteServiceServlet implements UpgradePackageProxyService {

@Override
public void addPackage(String fileName) {
HttpServletRequest request = getThreadLocalRequest();

boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);

try {
List items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (item.isFormField()) {
System.out.println(item.getFieldName());
System.out.println(item.getName());
System.out.println(item.getContentType());
System.out.println(item.isInMemory());
System.out.println(item.getSize());
} else {
fileName = item.getName();
if (fileName != null && !fileName.equals("")) {
fileName = FilenameUtils.getName(fileName);
File uploadedFile = new File("rootDirectory" + fileName);
try {
item.write(uploadedFile);
File newfile=new File(uploadedFile.getName());
uploadedFile.renameTo(newfile);
System.out.println(newfile.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}

}

Kris Sony
23 Jun 2011, 4:10 AM
I finally worked it out.

You need to set the formAction to a normal servlet
formPanel.setAction("https://localhost/upload");
formPanel.submit();


The servlet should be a normal HttpServlet and override the doPost

to easy :)