如何通过按钮单击i GWT下载文件?

时间:2010-09-10 12:40:11

标签: gwt

我有一个提供文件的servleta?

我正在构建一个带有“下载”按钮的页面,使用GWT。

如何让GWT客户端在onClick事件中下载文件?

P.S。 Anchor有效,但Button看起来更好。

4 个答案:

答案 0 :(得分:10)

如果您有文件地址。您可以打开如下窗口:

downloadButton.addClickHandler(new ClickHandler() {

    @Override
    public void onClick(ClickEvent event) {
        Window.open("http://127.0.0.1:8888/file.rar", "_self", "enabled");
    }
});

并且javadoc可以帮助您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

答案 1 :(得分:2)

我喜欢

Window.Location.replace("/downloadServlet");

答案 2 :(得分:1)

上述解决方案都没有为我工作,然后我意识到我已经有了实施工作。以下是我的表现方式:

Window.open(fileUrl, "_parent", "");

但关键在于你的servlet:

response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

此解决方案不会打开新窗口,而是直接打开"另存为"对话。两个世界中最好的。

答案 3 :(得分:0)

完整示例下载.xls文件USIGN GWT,apache-poi

    Environment : GWT SDK 2.4
    Spring 3.0.2M
    JAVA : 1.7

需要Jar文件来创建.xls文件:: 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

现在在用户点击按钮exportButton的浏览器中,控件导航到web.xml并搜索以/ myfiledownload结尾的url-pattern

的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>

在web.xml中执行代码后,控件尝试执行名为FileDownloadServlet的servlet

服务器端

    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