0

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!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Smile
  • 91
  • 2
  • 11
  • 1
    You're writing an empty byte array into your stream. You might want to at least use `in.read(buffer)`. – Thomas Sep 06 '22 at 07:31
  • @Thomas is right. The `read()` method returns a single byte, not the number of bytes that are read, and you don't read anything into `buffer`. The only reason you don't get any `IndexOutOfBoundsException` is because your buffer size is larger than the maximum unsigned byte value (255). – Rob Spoor Sep 06 '22 at 07:41
  • Thanks a lot! `@Thomas` is right.Thanks for your explantion,too.Thanks` @Rob Spoor` – Smile Sep 06 '22 at 08:51

0 Answers0