【springboot下载文件】

概要

springboot实现文件下载和导入

例如:

  • 下载导入模板,上传文件进行导入

文件下载

方式一:下载服务器上的文件模板

下面展示一些 文件下载工具类

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class FileUtils {
    public static void download(HttpServletResponse response, String filePath, String fileName){

        try {
            //通用的mime类型
            response.setContentType("application/octet-stream");
            //会出现文件名乱码问题
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            //以下设置请求头能解决下载的文件名乱码问题
            response.setHeader("Content-Disposition", "attachment;filename=;filename*=utf-8''"+URLEncoder.encode(fileName,"UTF-8"));
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
            writeBytes(is, response.getOutputStream());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void writeBytes(InputStream is, OutputStream os) {
        try {
            byte[] buf = new byte[1024];
            int len = 0;
            while((len = is.read(buf))!=-1)
            {
                os.write(buf,0,len);
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

controller接口层

    @ApiOperation("下载通讯录模板")
    @GetMapping("download_template")
    public Result download(HttpServletResponse httpServletResponse) {
        String fileName = "通讯录导入模板.xlsx";
        String filePath = "template/" + fileName;
        FileUtils.download(httpServletResponse,filePath,fileName);
        return Result.success();
    }

提示:要下载的文件要放在resource下,可创建自定义文件夹

方式二:通过代码创建excel响应给页面

例如:

  • 通过代码创建excel文件,通过流的方式响应给页面
// 创建一个新的工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");
        sheet.setDefaultColumnWidth(12);
        // 创建流量卡厂商选项列表
        TrafficCardManufacturerEnum[] manufacturers = TrafficCardManufacturerEnum.values();
        List<String> manufacturerOptions = new ArrayList<>();
        for (TrafficCardManufacturerEnum manufacturer : manufacturers) {
            manufacturerOptions.add(manufacturer.getLabel()); // 添加枚举值的名称到选项列表
        }
        // 创建下拉框单元格样式
        DataValidationHelper validationHelper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(manufacturerOptions.toArray(new String[0]));
        CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, 3, 3); // 假设有1000行数据,"性别"列是第二列(索引为1)
        DataValidation validation = validationHelper.createValidation(constraint, addressList);
        validation.setShowErrorBox(true);
        sheet.addValidationData(validation);
        // 创建表头行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("设备ID");
        // 创建设备名称单元格,并设置文字为红色
        Cell deviceNameCell = headerRow.createCell(1);
        deviceNameCell.setCellValue("设备名称");
        // 创建字体,并设置为红色
        Font font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.RED.getIndex()); // 字体颜色为红色
        // 创建样式,并将字体应用于样式
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);
        deviceNameCell.setCellStyle(cellStyle);
        headerRow.createCell(2).setCellValue("相机号");
        headerRow.createCell(3).setCellValue("流量卡厂商");
        headerRow.createCell(4).setCellValue("流量卡号");
        headerRow.createCell(5).setCellValue("username");
        headerRow.createCell(6).setCellValue("password");
        headerRow.createCell(7).setCellValue("dtu");
        headerRow.createCell(8).setCellValue("主板号");
        Cell notes = headerRow.createCell(9);
        notes.setCellValue("注:标记红色为必填,流量卡和流量卡厂商必须同时存在,设备ID不填时会自动生成,一次最多导入1000条");
        notes.setCellStyle(cellStyle);
        // 将工作簿写入ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();
        // 设置HTTP响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.xlsx");
        // 将Excel文件写入响应输出流
        ServletOutputStream outStream = response.getOutputStream();
        outStream.write(outputStream.toByteArray());
        outStream.flush();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值