Send a file from server to client in GWT

后端 未结 2 1999
萌比男神i
萌比男神i 2021-01-15 12:51

I am using GWT.

I have to download a file file from server to client.

Document is in the external repository.

Client sends the id o

2条回答
  •  深忆病人
    2021-01-15 13:04

    You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.

    Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box. But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                                                  throws ServletException, IOException { 
    
    String fileId = reguest.getParameter("fileId"); // value of file id from request
    File file = CreatorExel.getFile(fileId); // your method to create file from helper class
    
    // setting response headers
    response.setHeader("Content-Type", getServletContext().getMimeType(file.getName())); 
    response.setHeader("Content-Length", file.length()); 
    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); 
    
    BufferedInputStream input = null; 
    BufferedOutputStream output = null; 
    
    try { 
        InputStream inputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
    
        input = new BufferedInputStream(fileInput); 
        output = new BufferedOutputStream(outputStream); 
    
        int count;
        byte[] buffer = new byte[8192]; //  buffer size is 512*16
        while ((count = input.read(buffer)) > 0) {
             output.write(buffer, 0, count);
        }
    
    } finally { 
        if (output != null) {
           try { 
              output.close(); 
           } catch (IOException ex) {
           } 
        }
        if (input != null) {
           try { 
              input.close(); 
           } catch (IOException ex) {
           } 
        } 
    } 
    

提交回复
热议问题