yunus
yunus

Reputation: 121

how to get input stream from input stream file?

I have been developing a java web app and I want to add a download function. I want to download zip file located in "C:\apache-tomcat-6.0.36\webapps\xml\XML.zip". I have converted the file to InputStream, but I'm still confused how to get input stream data from the InputStream?

When I click the download button, it returns 0 (zero) byte of the zip file

Here is the controller to handle download zipfile :

@RequestMapping("download")
public String Download(HttpServletResponse response) {

    ZipInputStream zis = null;

    try {           

        InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip");
        zis = new ZipInputStream(is);

        response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType("application/zip");
        IOUtils.copy(zis.getInputStream, out);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    } 

    return null;
}

this line is causing the zero byte zip file:

IOUtils.copy(**zis.getInputStream**, out); 

Upvotes: 2

Views: 2798

Answers (2)

ppeterka
ppeterka

Reputation: 20726

If you want to get the whole ZIP file downloaded, you don't have to use ZipInputStream... That is for accessing the contents of the ZIP file...

Instead of zis.getInputStream() use is.getInputStream(), and remove the code related to the ZipInputStream:

@RequestMapping("download")
public String Download(HttpServletResponse response) {

  //ZipInputStream zis = null; no need for this

  try {           

    InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip");
    //zis = new ZipInputStream(is); //no need for this

    response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\"");
    OutputStream out = response.getOutputStream();
    response.setContentType("application/zip");
    IOUtils.copy(is, out); //no zis here, and "is" is already an InputStream instance
    out.flush();
    out.close();
  } catch (IOException e) {
    e.printStackTrace();
  } 

  return null;
}

Also, I'd revise the .close() calls: they are almost always best fit for finally blocks to ensure everzthing gets closed properly. (that, or try-with-resource blocks are to be used.)

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68433

Assuming that your code compiles:

If you are already picking up a zip file, there is no need to pass it through ZipInputStream again.

something like this http://www.avajava.com/tutorials/lessons/how-do-i-serve-up-a-pdf-from-a-servlet.html

Upvotes: 2

Related Questions