之前所用的下载文件方法总是出现下载文件未知大小的问题,百思不得其解,最后使用该方法后,问题解决。
// 根目录为resources
private static final String filePath = "/excel/xxx.xlsx";
/** * 下载EXCEL模板文件 * * @param response */ @ApiOperation(value = "下载EXCEL模板文件", notes = "下载EXCEL模板文件", httpMethod = "GET", produces = "application/vnd.ms-excel", protocols = "HTTP/1.1") @RequestMapping(value = "/download-excel-model", method = RequestMethod.GET) public void downloadImportTemplate(HttpServletResponse response) { try { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 获取所有匹配的文件 org.springframework.core.io.Resource[] resources = resolver.getResources(filePath); InputStream stream = resources[0].getInputStream(); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=xxx.xlsx"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { ex.printStackTrace(); } }
==============================================================================================================
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class DownloadExcelModel {
// 下载文件路径
private String filePath;
// 生成文件名称
private String fileName;
public DownloadExcelModel() {
}
public DownloadExcelModel(String filePath, String fileName) {
this.filePath = filePath;
this.fileName = fileName;
}
/**
* <p>
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
* 此版本生成2007以上版本的文件 (文件后缀:xlsx)
* </p>
*/
public void downloadExcelModel(HttpServletResponse response) throws Exception {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// 获取所有匹配的文件
org.springframework.core.io.Resource[] resources = resolver.getResources(filePath);
InputStream inputStream = resources[0].getInputStream();
// response缓冲区重置
response.reset();
// 支持下载参数
response.setContentType("application/vnd.ms-excel");
// 设置浏览器响应头对应的Content-disposition
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1) + ".xlsx");
// 设置响应编码
response.setCharacterEncoding("UTF-8");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
}