How to write FileInputStream to ServletOutputStream

Viewed 28

I want to download an image by servlet.
I can download the file.But the file is broken.
This is my servlet java file.

   @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String filePath = "D:\\programe\\code\\javaCode\\javaBase\\maven-demo-Servlet\\servletDown\\src\\main\\img.png";

        String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
        System.out.println(fileName);
        File file = new File(filePath);
        FileInputStream in = new FileInputStream(file);
        resp.setContentType("image/png");
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        int len;
        byte[] buffer = new byte[1024];
        ServletOutputStream outputStream = resp.getOutputStream();
        while ((len = in.read()) > 0) {
            outputStream.write(buffer, 0, len);
        }

        outputStream.flush();
        outputStream.close();
        in.close();
    }

I can down load file,but I get this.
enter image description here

the file size is 0 bytes.
I can look the img on server.Please help me!! thanks!

0 Answers
Related