JAVA实现下载resources下的文件

概述

 JAVA实现resources下的文件,本次实现的是下载一个模板文件。导入的包都是默认的io流这些。

首先在pom.xml引入包

             <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <nonFilteredFileExtensions>
                        <nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
                        <nonFilteredFileExtension>xls</nonFilteredFileExtension>
                        <nonFilteredFileExtension>docx</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>

 ExcelUtil工具类



import com.alibaba.nacos.common.utils.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.List;

public class ExcelUtil {

    private static Workbook appendTitles(Workbook wb, List<String> titles) throws Exception {

        Sheet sheet = wb.getSheetAt(0);
        // 设置表头的说明
        Row topRow = sheet.getRow(1);
        for (int i = 0; i < titles.size(); i++) {
            Cell cell = topRow.createCell(i + 6);
//            cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
            cell.setCellValue(titles.get(i));
            sheet.setColumnWidth( i + 6, titles.get(i).getBytes().length * 258);
        }
        return wb;
    }

    /**
     * 下载excel模板
     */
    public static void export(Workbook wb, String fileName, List<String> titles,
                              HttpServletResponse response) throws Exception {
        try {
            if(!CollectionUtils.isEmpty(titles)){
                wb = appendTitles(wb, titles);
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            wb.write(baos);
            baos.flush();
            byte[] aa = baos.toByteArray();
            response.addHeader("Content-Disposition",
                    "attachment;filename*=utf-8'zh_cn'" + fileName);
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.getOutputStream().write(aa);
            response.setContentLength(aa.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("write excel to stream error!", e);
        } finally {
            if (response.getOutputStream() != null) {
                response.getOutputStream().flush();
            }
        }
    }
}

ProjectConfiguration(扫描resources下面的文件)


import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

@Component
public class ProjectConfiguration {

    @Autowired
    private ResourceLoader resourceLoader;
    public static byte[] fileBytes;
    public static String fileName;

    @PostConstruct
    public void init(){
        Resource resource = resourceLoader.getResource("classpath:templates/areaTemplate.xls");
        try {
            InputStream inputStream = resource.getInputStream();
            fileName = "areaTemplate.xls";
            fileBytes = IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Controlleer控制层调用

 /**
     * 下载模板
     * */
    @CrossOrigin
    @PostMapping(value = "/downloadTemplate" , produces = {"application/json;charset=UTF-8"})
    public WeaResult downloadTemplate(HttpServletResponse response){
    byte[] fileSource = ProjectConfiguration.fileBytes;
    //防止对原数据进行操作
    byte[] fileBytes = Arrays.copyOf(fileSource, fileSource.length);
    //下载模板
    try {
      Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(fileBytes));
      List<String> titleList = new ArrayList();
      ExcelUtil.export(wb, ProjectConfiguration.fileName, titleList, response);
    } catch (Exception e) {
      
      e.printStackTrace();
    }
  }

测试(使用postman测试)

 

 

 可以看见就实现下载了resources下面的文件了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ybbgrain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值