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

该代码示例展示了如何在Java后端使用Servlet处理文件下载。通过设置响应头信息,包括Content-Type和Content-Disposition,确保浏览器以附件形式下载文件,并支持中文文件名。文件内容通过字节流读取并发送到前端。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

代码
    @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();
                }
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值