简体   繁体   中英

Java - File Download using HttpServletResponse - File gets corrupted after Download

I am trying to download file from my local file system after form submit. I am getting the FileInputStream and writing to the HttpServletResponse using the below code .

        PrintWriter out = response.getWriter();
        response.setCharacterEncoding("UTF-8");
        String filename = "DSR.xlsx";   
        response.setContentType("application/octet-stream");   
        response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   

        FileInputStream fileInputStream = new FileInputStream("C://Users/Metro/Desktop/DSR.xlsx");  

        int i;   
        while ((i=fileInputStream.read()) != -1) {  
        out.write(i);   
        }   
        fileInputStream.close();  
        out.close();

File is getting downloaded but file is corrupted . It works in case of text files only. I want the code to work in case of .xlsx, .pdf, .jpg etc.

Here the problem is with ContentType.

You have to set content type related to file extention.

For excel

response.setContentType("application/vnd.ms-excel")

For pdf

response.setContentType("application/pdf")

For jpg

response.setContentType("image/jpeg")

[refer this link to know all mime types]

https://www.sitepoint.com/mime-types-complete-list/

I resolved the issue using java.nio.file.Files.copy(Path source, OutputStream out).

        response.setCharacterEncoding("UTF-8");
        String filename = "DSR.xlsx";   
        response.setContentType("application/octet-stream");   
        response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   

        try (OutputStream out = response.getOutputStream()){
            File toBeCopied = new File("C://Users/Metro/Desktop/DSR.xlsx");
            Path path = toBeCopied.toPath();
            Files.copy(path, out);
            out.flush();
        }catch(IOException e){
            e.printStackTrace();
        }

It works in case of any file type (.jpg , .xlsx, .pdf )

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