简体   繁体   English

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

[英]Download a file in browser using java /spring

I am trying to download a file in browser using java. 我正在尝试使用Java在浏览器中下载文件。 The problem is i am not getting any error in code . 问题是我没有在代码中得到任何错误。 but the file is not getting download in the browser. 但文件无法在浏览器中下载。 I have reffrenced this site : http://www.codejava.net/frameworks/spring/spring-mvc-sample-application-for-downloading-file . 我已经介绍了这个站点: 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();

It may be because you are adding 1000 more byes to the content length. 可能是因为您要为内容长度增加1000个再见。 So, the browser is actually waiting to get all the bytes as mentioned in the Content-Length header. 因此,浏览器实际上正在等待获取Content-Length标头中提到的所有字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM