Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a user download a file in client side (Google Web Toolkit)

Tags:

download

gwt

I'm using GWT(Google Web Toolkit) to make a website. I need to show a table to the user, and let the user download the contents of the table.

On the client side, how can a user download a file when they press the "download" button?

The "Download" button has an onClick() listener. And the client side class extends Composite.

I've tried to make the class extend HttpServlet, but it becomes too complicate.

I already read posts here:

  1. http://www.mkyong.com/java/how-to-download-file-from-website-java-jsp/
  2. How to use GWT when downloading Files with a Servlet?

But I still don't know how can I provide downloadable file to the user on the client side.

like image 518
Seongeun So Avatar asked Dec 05 '12 14:12

Seongeun So


2 Answers

You REALLY need to distinguish between GWT client side java code and server side java code.

On the client side in your GWT Java Code

String url = GWT.getModuleBaseURL() + "downloadService?fileInfo1=" + fileInfo1;
Window.open( url, "_blank", "status=0,toolbar=0,menubar=0,location=0");

On server side in your non-gwt Java code-

In web.xml

<servlet>
    <servlet-name>downloadService</servlet-name>
    <servlet-class>AAA.BBB.CCC.DownloadServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>downloadService</servlet-name>
    <url-pattern>/<gwtmodulename>/downloadService</url-pattern>
</servlet-mapping>

In server package code a servlet

    public class DownloadServlet extends HttpServlet{
    protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
        {
            String fileName = req.getParameter( "fileInfo1" );

            int BUFFER = 1024 * 100;
            resp.setContentType( "application/octet-stream" );
            resp.setHeader( "Content-Disposition:", "attachment;filename=" + "\"" + fileName + "\"" );
            ServletOutputStream outputStream = resp.getOutputStream();
            resp.setContentLength( Long.valueOf( getfile(fileName).length() ).intValue() );
            resp.setBufferSize( BUFFER );
            //Your IO code goes here to create a file and set to outputStream//

        }
    }

Ensure you push your file contents to **outputStream** .

like image 65
appbootup Avatar answered Oct 26 '22 18:10

appbootup


If you know the path of the file, Code snippet is shown below.

button.addClickHandler(new ClickHandler()  
{ 

    @Overrid
    public void onClick(ClickEvent event) 
    {
        Window.open(GWT.getHostPageBaseURL() + "/file.rar", "name", "enabled");
    }
});
like image 30
Adarsha Avatar answered Oct 26 '22 17:10

Adarsha