2

我正在使用 GWT。

我必须将文件文件从服务器下载到客户端

文档位于外部存储库中。

客户端通过 Servlet 发送文档的 ID。

服务器端:使用此 ID 文档检索:

Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();

ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();

int c;
while ((c = inputStream.read()) != -1) {
    System.out.print((char) c); 
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();

在这里我可以阅读文档。

我想把这个发给客户。如何将其制作为文件并将其发送回客户端?

4

2 回答 2

3

在您的 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; 
于 2012-08-24T14:18:16.867 回答
1

您可以在服务器端创建一个标准 servlet(扩展HttpServlet而不是扩展RemoteServiceServlet),并有机会在客户端将 id 作为 servlet 参数提交。

现在您需要在收到请求后创建 excel 文件并将其发送给客户端。浏览器会自动弹出下载对话框。但是您应该确保设置正确的内容类型响应标头。此标头将指示浏览器它是哪种类型的文件。

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) {
       } 
    } 
} 
于 2012-08-24T14:20:58.567 回答