简体   繁体   English

下载文件时使用PrintWriter

[英]Using PrintWriter while downloading a file

I have a requirement, where i need to process a set of files and create a compressed zip file out of it and then use it for download. 我有一个要求,我需要处理一组文件并从中创建一个压缩的zip文件,然后将其用于下载。 I am using a Servlet for downloading that file, but the download takes quite sometime. 我正在使用Servlet下载该文件,但是下载需要花费相当长的时间。 So i want the user to know that the servlet is processing the request through a print writer output messsage instead of showing him a blank screen.But everytime i use a printwriter to write something to the screen, the message takes a lot of time to show on the screen and the file doesnt download. 所以我想让用户知道servlet正在通过打印书写器输出消息处理消息,而不是向他显示空白屏幕。但是每次我使用打印书写器向屏幕写东西时,该消息都需要花费很多时间才能显示在屏幕上,该文件不会下载。 How can i achieve this? 我怎样才能做到这一点? Any ides? 有想法吗? Thanks. 谢谢。

Here's my code 这是我的代码

OutputStream oStream = null;
    DataInputStream dInput = null;
    File file = new File(("PATH"));
    int length = 0;
    try{
        DownloadServerLogs.processLogs();
        oStream = res.getOutputStream();
        res.setContentType("application/zip");
        res.setContentLength((int)file.length());
        res.setHeader("Content-Disposition",
                         "attachment;filename=\"" + file.getName() + "\"" );
        byte[] bbuf = new byte[BYTES_DOWNLOAD];
        dInput = new DataInputStream(new FileInputStream(file));

        while ((dInput != null) && ((length = dInput.read(bbuf)) != -1))
        {
            oStream.write(bbuf,0,length);
        }
        dInput.close();
        oStream.flush();
        oStream.close();
    }catch(Exception e){
        Utility.getLogger().error(e.getMessage(), e);
    }

我猜最好通过使用Javascript之类的消息向客户端显示消息(假设您正在使用AJAX来调用servlet)。

Well, it's probably not that safe to do it that way. 好吧,以这种方式做可能并不安全。 I'd have a look at the answer below. 我将看看下面的答案。 Not that it's your exact problem, but might be similar. 这不是您的确切问题,但可能类似。

Most efficient way to create InputStream from OutputStream 从OutputStream创建InputStream的最有效方法

Effectively, you are reading and writing on the same thread and my guess is that with the addition of the PrintWriter you are getting deadlocked somewhere. 实际上,您正在同一线程上进行读取和写入,我的猜测是,随着PrintWriter的添加,您将陷入某个地方的僵局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM