PDA

View Full Version : file upload example



g1_
15 Jan 2010, 6:01 AM
Does anyone have an example of file uploads (both client and server side)?

I've taken the code from the explorer as a starting point for the client:



final FormPanel panel = new FormPanel();
panel.setHeaderVisible(false) ;
panel.setBodyBorder(false) ;
panel.setAction("/voipconnect2/upload") ;
panel.setEncoding(Encoding.MULTIPART);
panel.setMethod(Method.POST);
panel.setButtonAlign(HorizontalAlignment.CENTER);

FileUploadField file = new FileUploadField() ;
file.setAllowBlank(false) ;
file.setFieldLabel("File") ;
//file.setName("test.gif") ;
panel.add(file) ;

Button btn = new Button("Upload") ;
btn.addSelectionListener(new SelectionListener<ButtonEvent>() {

@Override
public void componentSelected(ButtonEvent ce) {
if (!panel.isValid()) {
return ;
}

// normally would submit the form but for example no server set up to
// handle the post
panel.submit();

MessageBox.info("Action", "Your file was uploaded", null);
}
});
panel.addButton(btn) ;



and the server side is based on the apache commons stuff:



public class UploadServlet extends HttpServlet {

...

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
app.log("UploadServlet","Receiving file upload") ;
FileItemFactory factory=new DiskFileItemFactory() ;
ServletFileUpload upload=new ServletFileUpload(factory) ;
List items=null ;
try {
items=upload.parseRequest(request) ;
app.log("UploadServlet","number of items uploaded: "+items.size()) ;
} catch (FileUploadException e) {
e.printStackTrace() ;
}
Iterator it=items.iterator() ;
while(it.hasNext()) {
FileItem item= (FileItem) it.next() ;
File uploadedFile=new File("/var/www/vop/images/profile/"+item.getName()) ;
try {
item.write(uploadedFile) ;
} catch (Exception e) {
e.printStackTrace() ;
}
}
}

//---------------


}//end: class