I hava a servleta that serves files?
I\'m building a page with a \"Download\" button usung a GWT.
How to make a GWT client download a file in an onClick even
COMPLETE EXAMPLE TO DOWNLOAD a .xls FILE USIGN GWT,apache-poi
Environment : GWT SDK 2.4
Spring 3.0.2M
JAVA : 1.7
Needed Jar file to create .xls file :: poi-3.0.1-FINAL.jar
exportButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String link = GWT.getModuleBaseURL() + "myfiledownload";
Window.open(link , "", "");
}//onClick
});//addClickHandler
Now at the browser when the user hits button exportButton then the control navigates to web.xml and searches for url-pattern that ends with /myfiledownload
web.xml
<servlet>
<servlet-name>fileDownload</servlet-name>
<servlet-class>com.sbabamca.server.FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileDownload</servlet-name>
<url-pattern>/app/myfiledownload</url-pattern>
</servlet-mapping>
After execuiting the code in web.xml the controls tries to execute the servlet with name FileDownloadServlet
FileDownloadServlet.java
------------------------
package com.sbabamca.server;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.metadata.ClassMetadata;
import com.fpix.hibernate.util.HibernateUtil;
import com.fpix.util.date.MyDate;
import java.io.IOException;
import java.util.ArrayList;
public class MyFileServlet extends HttpServlet {
SessionFactory sessionFactory;
Session session;
Transaction tx = null;
@SuppressWarnings({ "unchecked", "deprecation" })
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=users.xls");
try {
sessionFactory = HibernateUtil.getSessionFactory();
if(!sessionFactory.getCurrentSession().isOpen())
{
session = sessionFactory.openSession();
}
else
{
session = sessionFactory.getCurrentSession();
}
tx = session.beginTransaction();
tx.begin();
Query qry = session.createQuery("from com.fpix.dto.User u ");
ArrayList<com.fpix.dto.User> u = (ArrayList<com.fpix.dto.User>)qry.list();
Query qry1 = session.createQuery("from com.fpix.dto.Profile p ");
ArrayList<com.fpix.dto.Profile> p = (ArrayList<com.fpix.dto.Profile>)qry1.list();
/*
* code to get the column name of User and Profile Entity
*/
ClassMetadata cm = sessionFactory.getClassMetadata(com.fpix.dto.User.class);
String userAttributes[] = cm.getPropertyNames();
ClassMetadata cm1 = sessionFactory.getClassMetadata(com.fpix.dto.Profile.class);
String profileAttributes[] = cm1.getPropertyNames();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("id");
/*
* code to create the columns names in .xls file
*/
int j = 0;
for(int i=0;i<userAttributes.length;i++){
j = i;
if(!userAttributes[i].equalsIgnoreCase("profileData") )
rowhead.createCell((short) ++j).setCellValue(userAttributes[i]);
}//for
for(int i=0;i<profileAttributes.length;i++){
if(!profileAttributes[i].equalsIgnoreCase("userData"))
rowhead.createCell((short) ++j).setCellValue(profileAttributes[i]);
}//for
int index = 1;
for(int i=0;i<u.size();i++){
HSSFRow row = sheet.createRow((short) index);
row.createCell((short) 0).setCellValue(u.get(i).getId());
row.createCell((short) 1).setCellValue(u.get(i).getUser());
row.createCell((short) 2).setCellValue(u.get(i).getPassWord());
row.createCell((short) 3).setCellValue(u.get(i).getType());
row.createCell((short) 4).setCellValue(u.get(i).getRole());
row.createCell((short) 5).setCellValue(u.get(i).getProfile());
row.createCell((short) 6).setCellValue(u.get(i).getEmail());
row.createCell((short) 7).setCellValue(MyDate.timeStampToString(u.get(i).getDor()));
// set the Profile data to the excel sheet cells
row.createCell((short) 8).setCellValue(p.get(i).getRollNo());
row.createCell((short) 9).setCellValue(p.get(i).getFname());
row.createCell((short) 10).setCellValue(p.get(i).getLname());
row.createCell((short) 11).setCellValue(MyDate.timeStampToString(Long.parseLong(p.get(i).getDoj())));
row.createCell((short) 12).setCellValue(MyDate.timeStampToString(Long.parseLong(p.get(i).getDob())));
row.createCell((short) 13).setCellValue(p.get(i).getBloodGroup());
row.createCell((short) 14).setCellValue(p.get(i).getPhoto());
row.createCell((short) 15).setCellValue(p.get(i).getPhone1());
row.createCell((short) 16).setCellValue(p.get(i).getPhone2());
row.createCell((short) 17).setCellValue(p.get(i).getAddress());
row.createCell((short) 18).setCellValue(p.get(i).getCity());
row.createCell((short) 19).setCellValue(p.get(i).getPin());
row.createCell((short) 20).setCellValue(p.get(i).getState());
row.createCell((short) 21).setCellValue(p.get(i).getCountry());
row.createCell((short) 22).setCellValue(p.get(i).getGrade());
row.createCell((short) 23).setCellValue(p.get(i).getGroups());
row.createCell((short) 24).setCellValue(p.get(i).getAssignCourse());
index++;
}//for
java.io.OutputStream out = resp.getOutputStream();
wb.write(out);
out.close();
System.out.println("Data is Exported to Excel file.");
}//try
catch (Exception e) {
System.out.println(" Data cannot be imported :: getImport() :: ImportExportData "+e);
}//catch
}//doGet
}//class
if you have the file address. You can open a window like below:
downloadButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.open("http://127.0.0.1:8888/file.rar", "_self", "enabled");
}
});
and that javadoc can help you http://google-web-toolkit.googlecode.com/svn/javadoc/2.1/com/google/gwt/user/client/Window.html#open%28java.lang.String,%20java.lang.String,%20java.lang.String%29
I like
Window.Location.replace("/downloadServlet");
None of the solutions above worked for me, then I realized I already have an implementation working. Here's how I do it:
Window.open(fileUrl, "_parent", "");
But the key is in your servlet:
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
This solution will NOT open new window and instead directly opens the "Save As" dialog. Best of both worlds imo.