java文件下载

public void fileDownload(String filePath, String fileName, HttpServletResponse response) throws IOException {
        //拼接服务器真实路径
        String realFilePath = PathUtil.getClasspath() + "uploadFiles/" + filePath;
        File file = new File(realFilePath);
        if (file.exists()) {
            int fileLength = (int) file.length();
            if (fileLength != 0) {
                //获取文件拓展名
                String suffix = filePath.substring(filePath.lastIndexOf("."));
                //自定义文件名
                String realFileName = fileName + suffix;
                realFileName = new String(realFileName .getBytes(), "ISO-8859-1");
                response.reset();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=" + realFileName);
                response.setContentLength(fileLength);
                InputStream is = new FileInputStream(realFilePath);
                byte[] buffer = new byte[1024];
                ServletOutputStream fos = response.getOutputStream();
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.flush();
                fos.close();
            }
        }
    }
posted @ 2021-05-27 09:41  路暝月  阅读(6)  评论(0编辑  收藏  举报  来源