user1733583
user1733583

Reputation:

Error while file download

in my servlet, I am passing a file path using cookies and downloading a file as below

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String b = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
         for (Cookie cookie : cookies) {
           if (cookie.getName().equals("thecookie")) {
               b = cookie.getValue();
            }
          }
        }

    BufferedReader br = new BufferedReader(new FileReader(b+"/logs.txt"));
    String path = br.readLine();
    br.close();

    File file = new File(path+"/Results.xlsx");
    FileInputStream fileIn = new FileInputStream(file);
    ServletOutputStream out = response.getOutputStream();

    byte[] outputByte = new byte[4096];
    //copy binary contect to output stream
    while(fileIn.read(outputByte, 0, 4096) != -1)
    {
        out.write(outputByte, 0, 4096);
    }
    fileIn.close();
    out.flush();
    out.close();
}

Everything works fine and the file is getting downloaded but, I want to download Results.xlsx and the file that is being downloaded is download.zip and this download.zip is same size as my Results.xlsx file but is not getting opened by excel.

How do I do this right??

Upvotes: 0

Views: 177

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

You're writing the data to the output stream, but you're not setting a content type or a filename. You should use:

response.setHeader("Content-Disposition", "attachment; filename=Result.xslx");
response.setContentType(
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

(Before you start writing to the output stream.)

Additionally, your stream-copying loop is broken - you're always writing out 4096 bytes even if you haven't read that much. It should be:

int bytesRead;
while((bytesRead = fileIn.read(outputByte)) != -1)
{
    out.write(outputByte, 0, byteRead);
}

... and you should use a try-with-resources or finally block to make sure you close your stream even if there's an exception.

(Or use a utility method from a library such as Guava.)

Upvotes: 2

Related Questions