Как скачать файл нажатием кнопки i GWT? - PullRequest
5 голосов
/ 10 сентября 2010

У меня есть сервлета, которая обслуживает файлы?

Я создаю страницу с помощью кнопки «Загрузить», используя GWT.

Как заставить клиента GWT загружать файл в событии onClick?

P.S. Якорь работает, но Баттон выглядит лучше.

Ответы [ 4 ]

10 голосов
/ 10 сентября 2010

если у вас есть адрес файла. Вы можете открыть окно, как показано ниже:

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. Строка,% 20java.lang.String,% 20java.lang.String% 29

2 голосов
/ 06 ноября 2013

Мне нравится

Window.Location.replace("/downloadServlet");
1 голос
/ 20 декабря 2014

Ни одно из приведенных выше решений не сработало для меня, тогда я понял, что у меня уже есть работающая реализация Вот как я это делаю:

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

Но ключ в вашем сервлете:

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

Это решение НЕ откроет новое окно и вместо этого откроет диалоговое окно «Сохранить как». Лучшее из обоих миров имо.

0 голосов
/ 03 марта 2013

ПОЛНЫЙ ПРИМЕР ДЛЯ ЗАГРУЗКИ ФАЙЛА ИСПОЛЬЗОВАНИЯ ФАЙЛА .xls, 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 и ищет шаблон URL, который заканчивается на / 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>

После выполнения кода в web.xml элементы управления пытаются выполнить сервлет с именем FileDownloadServlet

SERVER SIDE

    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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...