简体   繁体   中英

Check if stream from HttpServletResponse was download by client - JAVA

Basically, my system generates url's to download files from my server. I make this using Struts with a result of type 'stream'. This work great. Now I want to notice for each file downloaded, if it was FULLY downloaded.

I've been searching for a while but really don't know how to continue. I'm a beginner with this.

**

New Action:

**

  public String download(){
  try {
            String path = Init.getWebInfPath() + UploadManager.getInstance().getProperty("UPLOAD_DIR") + content.getZipFile();
            file = new FileInputStream(new File(path));
        } catch (Exception e) {
            return ERROR;
        }

        Long overallSize = null;
        try {
            overallSize = file.getChannel().size();
        } catch (IOException e) {
            e.printStackTrace();
        }

        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename=\""+content.getZipFile()+"\"");
        response.setHeader("Content-Length", String.valueOf(overallSize));

        ServletOutputStream sos = null;
        try {
            sos = response.getOutputStream();
            int read;
            read = file.read();
            while (read>0){
                sos.write(read);
                read = file.read();
            }
        } catch(Exception e){
          return ERROR;      
        }

        return NONE;

}

**

New xml:

**

<struts>
     <package name="content" namespace="/content" extends="default">
    <action name="download" class="com.tictapps.adserver.web.content.ContentAction" method="download">
        <result name="none"/>
    </action>
</package>
</struts>

Once you return the stream result, you've no more control on the OutputStream.

The first ways coming to my mind to ensure that the file is completely downloaded are:

  1. Write directly to the OutputStream, and return the result NONE (that is mapped to nothing) instead of SUCCESS (that you've mapped to Stream). You will have full control on the response, but will lose some of the framework automatisms. This works, I've did it in the past .

  2. Create a custom result based on the Stream result's source code, eg. StreamWithConfirm , and add the logic you need in it.

  3. You could probably do it in a custom interceptor (in the post-invocation part, obviously), but I'm not sure and BTW this would be the hardest of the three for a newbie.

The n. 1 (adapting the code from the linked answer) should be what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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