Send a file from server to client in GWT

后端 未结 2 2000
萌比男神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) {
           } 
        } 
    } 
    
    0 讨论(0)
  • 2021-01-15 13:26

    In Your Servlet:

    Document document =(Document)session.getObject(docId);
    ContentStream contentStream = document.getContentStream();
    String name = contentStream.getFileName();
    response.setHeader("Content-Type", "application/octet-stream;");
    response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
    OutputStream os = response.getOutputStream();
    InputStream is = 
      (ByteArrayInputStream) contentStream.getStream();
    BufferedInputStream buf = new BufferedInputStream(is);
    int readBytes=0;
    while((readBytes=buf.read())!=-1) {
          os.write(readBytes);
    }   
    os.flush();
    os.close();// *important*
    return; 
    
    0 讨论(0)
提交回复
热议问题