java发送文件到网页并从网页下载文件

从网页下载文件时,可以使用虚拟映射地址,也可以直接将文件以响应流的方式发送给前端。

代码

    @Value("${excel.path}")
    private String excelPath;

 @RequestMapping(value = "/assist/excel", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE)
    public EiInfo downloadAssistExcel(final HttpServletResponse response) throws Exception {
        // 获取文件
        String fileName = "外协单位年度安全教育-人员清单模板.xls";
        File file = new File(excelPath + fileName);
        boolean b = downloadFile(file, fileName, response);
        if (b) {
            return ReturnOutInfo.outInfoSuccess(new EiInfo(), "下载成功");
        } else {
            return ReturnOutInfo.outInfoFailure(new EiInfo(), "下载失败");
        }
    }
private boolean downloadFile(File file, String fileName, HttpServletResponse response) throws Exception {
        // 清空缓冲区,状态码和响应头(headers)
        response.reset();
        // 设置ContentType,响应内容为二进制数据流,编码为utf-8,此处设定的编码是文件内容的编码
        response.setContentType("application/octet-stream;charset=utf-8");
        // 以(Content-Disposition: attachment; filename="filename.jpg")格式设定默认文件名,设定utf编码,此处的编码是文件名的编码,使能正确显示中文文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ";filename*=utf-8''" + URLEncoder.encode(fileName, "utf-8"));

        // 实现文件下载
        byte[] buffer = new byte[1024 * 1024 * 1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            // 获取字节流
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            LOGGER.info("Download successfully!");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("Download failed!");
            return false;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

你可能感兴趣的:(java,开发语言)