使用java / spring在浏览器中下载文件

时间:2015-10-27 18:38:17

标签: java spring servlets httpresponse

我正在尝试使用java在浏览器中下载文件。问题是我没有在代码中收到任何错误。但该文件未在浏览器中下载。 我已经改编了这个网站:http://www.codejava.net/frameworks/spring/spring-mvc-sample-application-for-downloading-file

        ServletContext context = request.getServletContext();
        String appPath = context.getRealPath("");
        String filePat="pat of the file";
        File downloadFile = new File(filePath);
        System.out.println("downloadFile path: "+ filePath);
        FileInputStream inputStream = new FileInputStream(downloadFile);

     // get MIME type of the file
        String mimeType = context.getMimeType(fullPath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
        response.setHeader(headerKey, headerValue);

        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        System.out.println("buffer: "+ buffer.length);
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
        int counter=0;
        while ((bytesRead = inputStream.read(buffer))!=-1  ) {
            counter++;
            System.out.println("counter: "+ counter+ "bytesRead:"+bytesRead);
            outStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outStream.close();

1 个答案:

答案 0 :(得分:0)

可能是因为您在内容长度上添加了1000多个字节。因此,浏览器实际上正在等待获取Content-Length标头中提到的所有字节。