Springboot实现文件上传下载功能
一、文件上传
1. controller层
@RestController
@RequestMapping(value = "/excel")
public class UploadController {
@Autowired
private UploadExcelPoiService uploadExcelPoiService; /**
* 导入excel文件
*
* @param file param
* @return rep
* @throws ApplicationException ex
*/
@PostMapping("/temporaryIncentive/import")
@ResponseBody
ResponseVO<List<List<MonthValueVO>>> importIncentive(@RequestParam("file") MultipartFile file)
throws ApplicationException {
return uploadExcelPoiService.importTemporaryIncentive(file);
}
}
2. service层
@Service
public class UploadExcelPoiService implements IUploadExcelPoiService {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelTaskService.class); /**
* import TemporaryIncentive
*
* @param file param
* @return ResponseVO
* @throws ApplicationException ex
*/
@Override
public ResponseVO<List<List<MonthValueVO>>> importTemporaryIncentive(MultipartFile file)
throws ApplicationException {
if (file == null) {
return ResponseUtil.resultError("com.xxx.it.iprice.00010104", new ArrayList<>());
}
String fileName = file.getOriginalFilename();
if (fileName == null) {
return ResponseUtil.resultError("com.xxx.it.iprice.00010105", new ArrayList<>());
} if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
return ResponseUtil.resultError("com.xxx.it.iprice.00010105", new ArrayList<>());
} boolean isExcel2003 = !fileName.matches("^.+\\.(?i)(xlsx)$");
List<List<MonthValueVO>> monthList = new LinkedList<>();
File outputFile = null;
try {
String outputFilePath = System.getProperty("java.io.tmpdir") + fileName;
outputFile = new File(outputFilePath);
file.transferTo(outputFile);
LOGGER.info("上传文件名{}, 路径{}", fileName, outputFile.getAbsolutePath());
InputStream is = new FileInputStream(outputFile);
Workbook wb;
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
Sheet sheet = wb.getSheetAt(0);
if (sheet == null) {
return ResponseUtil.resultError("com.xxx.it.iprice.00010106", new ArrayList<>()); }
int lastRowNum = sheet.getLastRowNum();
if (lastRowNum <= 0) {
return ResponseUtil.resultError("com.xxx.it.iprice.00010107", new ArrayList<>());
} // 读取首行
Row row0 = sheet.getRow(0);
if (row0 == null) {
return ResponseUtil.resultError("com.xxx.it.iprice.00010107", new ArrayList<>());
} int lastCloNum = row0.getPhysicalNumberOfCells();
List<MonthValueVO> singleList = new LinkedList<>(); int rateIndex = 3; // 共lastCloNum-rateIndex+1个月
for (int c = rateIndex; c <= lastCloNum; c++) {
String month = row0.getCell(c).getStringCellValue();
MonthValueVO tmp = new MonthValueVO();
tmp.setMonth(month);
singleList.add(tmp);
}
for (int r = 1; r <= lastRowNum; r++) {
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
List<MonthValueVO> monthValueVoList = new LinkedList<>();
for (int colIdx = rateIndex; colIdx <= lastCloNum; colIdx++) {
String monthRate = row.getCell(colIdx).getStringCellValue();
if (!BasicUtil.isValid(monthRate)) {
throw new ExcelImportException("com.xxx.it.iprice.00010108", r + 1, colIdx + 1);
}
MonthValueVO monthValueVo = new MonthValueVO();
monthValueVo.setMonth(singleList.get(colIdx - rateIndex).getMonth());
monthValueVo.setValue(monthRate.substring(0, monthRate.length() - 1));
monthValueVoList.add(monthValueVo);
}
monthList.add(monthValueVoList);
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (outputFile != null) {
outputFile.delete();
}
} return ResponseUtil.resultSuccess(monthList);
}
}
3. postman调试

二、文件下载
1. 服务接口
@GET
@Path("/temporaryIncentive/export")
@Consumes(MediaTypes.JSON_UTF8)
void exportTemporaryIncentive(@QueryParam("sortType") String sortType, @QueryParam("versionId") String versionId,
@Context HttpServletRequest req, @Context HttpServletResponse resp) throws ApplicationException;
2. 服务实现
private void exportIncentiveToExcel(List<VerticalPriceVO> verticalPriceList, HttpServletRequest req,
HttpServletResponse resp) {
if (verticalPriceList == null || verticalPriceList.size() <= 0) {
return;
}
XSSFWorkbook inWb = new XSSFWorkbook();
final XSSFSheet inSheet = inWb.createSheet("Temporary Incentive");
int rowIdx = 0;
int colIdx = 0;
XSSFRow row1 = inSheet.createRow(rowIdx);
final CellStyle dataLStyle = setDataCellStyle(inWb, 8, HorizontalAlignment.LEFT, true);
final CellStyle dataRStyle = setDataCellStyle(inWb, 8, HorizontalAlignment.RIGHT, true); createCell("临时激励", dataLStyle, colIdx, row1);
colIdx += 3;
VerticalPriceVO single = verticalPriceList.get(0);
List<MonthValueVO> monthValueVoList = single.getTempIncentiveRate();
for (MonthValueVO monthValueVo : monthValueVoList) {
createCell(monthValueVo.getMonth(), dataRStyle, colIdx, row1);
colIdx++;
}
rowIdx++; // 先将所有渠道类型国际化信息查到本地,减少服务调用
Map<String, String> categoryMap = new HashMap<>();
try {
List<LookupItemVO> channelCategoryList =
lookupItemQueryService.findItemListByClassify(LookupConstants.CHANNEL_CATEGORY);
categoryMap = channelCategoryList.stream()
.collect(Collectors.toMap(item -> item.getItemCode() + item.getLanguage(), LookupItemVO::getItemName));
} catch (ApplicationException e) {
LOGGER.error("getCountryRegionPricingList error --- ", e);
}
if (categoryMap.size() <= 0) {
LOGGER.error("------------ categoryMap.size()<=0 ----------------");
return;
}
for (VerticalPriceVO ele : verticalPriceList) {
XSSFRow inRow = inSheet.createRow(rowIdx);
List<MonthValueVO> tempIncentiveRateList = ele.getTempIncentiveRate();
String lang = CommonUtils.getLanguage();
String channelTypeName = categoryMap.get(ele.getChannelType() + lang);
String[] productArr = new String[] {ele.getOfferingName(), channelTypeName, ele.getDirectAccountName()};
int colIndex = 0;
for (; colIndex < productArr.length; colIndex++) {
createCell(productArr[colIndex], dataLStyle, colIndex, inRow);
}
for (MonthValueVO monthValueVo : tempIncentiveRateList) {
String tempIncentiveRate = monthValueVo.getValue();
String percent = BasicUtil.isBigDecimal(tempIncentiveRate);
createCell(percent, dataRStyle, colIndex, inRow);
colIndex++;
}
rowIdx++;
}
String fileName = "临时激励";
if (Constants.LANGUAGE_EN_US.equalsIgnoreCase(CommonUtils.getLanguage())) {
fileName = "temporaryIncentive";
}
writeToExcel(inWb, req, resp, fileName);
}
/**
* 写入excel
*
* @param workBook param
* @param req param
* @param resp param
* @param name param
*/
public void writeToExcel(XSSFWorkbook workBook, HttpServletRequest req, HttpServletResponse resp, String name) {
DateFormat dfNow = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = name + BasicUtil.UNDERLINE + dfNow.format(new Date()) + ".xlsx";
String checkPath = StringVerifyUtil.dealSpecialChar(fileName);
File outputFile = new File(checkPath);
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
workBook.write(out); // 保存Excel文件
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (out != null) {
try {
// 关闭文件流
out.close();
} catch (IOException ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
} downloadExcel(req, resp, outputFile);
} private void downloadExcel(HttpServletRequest req, HttpServletResponse resp, File file) {
InputStream in = null;
DownloadOutput download = new DownloadOutput();
try {
// 尝试下载文件
// 根据浏览器判断下载文件名转义
String agent = req.getHeader("User-Agent").toLowerCase();
File checkFile = StringVerifyUtil.getValidDirectoryPath(file);
in = new FileInputStream(checkFile);
if (agent.contains("msie") || agent.contains("trident")) {
download.outputFromStream(req, resp, in, file.getName(), true, 0L);
} else {
download.outputFromStream(req, resp, in,
new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), false,
0L);
}
} catch (FileNotFoundException e) {
LOGGER.error("file: {} not found -- ", file.getPath(), e);
} catch (Exception e) {
LOGGER.error("{} download error -- ", file.getPath(), e);
} finally {
StreamUtil.closeStreams(in);
if (in != null) {
try {
in.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
if (file.delete()) {
LOGGER.info("{} delete success -- ", file.getPath());
}
}
3. postman测试

Springboot实现文件上传下载功能的更多相关文章
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- JavaWeb实现文件上传下载功能实例解析 (好用)
转: JavaWeb实现文件上传下载功能实例解析 转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web ...
- SpringBoot图文教程4—SpringBoot 实现文件上传下载
有天上飞的概念,就要有落地的实现 概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例 文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例 ...
- WEB文件上传下载功能
WEB文件上传下载在日常工作中经常用到的功能 这里用到JS库 http://files.cnblogs.com/meilibao/ajaxupload.3.5.js 上传代码段(HTML) <% ...
- Struts2实现文件上传下载功能(批量上传)
今天来发布一个使用Struts2上传下载的项目, struts2为文件上传下载提供了好的实现机制, 首先,可以先看一下我的项目截图 关于需要使用的jar包,需要用到commons-fileupload ...
- php实现文件上传下载功能小结
文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...
- 文件一键上传、汉字转拼音、excel文件上传下载功能模块的实现
----------------------------------------------------------------------------------------------[版权申明: ...
- C# 文件上传下载功能实现 文件管理引擎开发
Prepare 本文将使用一个NuGet公开的组件技术来实现一个服务器端的文件管理引擎,提供了一些简单的API,来方便的实现文件引擎来对您自己的软件系统的文件进行管理. 在Visual Studio ...
- javaweb项目中的文件上传下载功能的实现
框架是基于spring+myBatis的. 前台页面的部分代码: <form action="${ctx}/file/upLoadFile.do"method="p ...
- FasfDFS整合Java实现文件上传下载功能实例详解
https://www.jb51.net/article/120675.htm 在上篇文章给大家介绍了FastDFS安装和配置整合Nginx-1.13.3的方法,大家可以点击查看下. 今天使用Java ...
随机推荐
- wps - Word文档打开后不能编辑
Word文档打开后不能编辑 解决方式 [审阅]-[限制编辑]-[设置文档的保护方式]-[修订]-[启动保护]-[停止保护] Word文档打开后不能编辑,可以这样处理 打开Word文档后,发现无法输入内 ...
- Centos 7 部署Kubernetes集群 (基于cri-dockerd)
前言 基础描述 从 k8s 1.24开始,dockershim已经从kubelet中移除,但因为历史问题docker却不支持kubernetes主推的CRI(容器运行时接口)标准,所以docker不能 ...
- 题解[CF674D]Bearish_Fanpages
题意 原意简述版 有 \(n\) 个公司,每个公司在某社交媒体拥有一个粉丝专页.该社交媒体推出了"关注"功能,每个粉丝专页必须"关注"一个粉丝专页,保证不会有自 ...
- beego框架中的注解路由不生效的问题
在测试中发现 使用注解路由的话 项目需要在gopath路径下的src下才可以 并且配置文件的 runmode = dev 然后执行bee run 在路由文件夹里才会生成commentRouter文件 ...
- docker下载java镜像,执行xxx.jar文件
docker pull java:8u111
- GPS授时仪(网络校时服务器)成功投运攀枝花市中西医结合医院
GPS授时仪(网络校时服务器)成功投运攀枝花市中西医结合医院 技术交流:岳峰 15901092122 论述当下网络时间同步的重要性 北京华人开创公司 技术交流15901092122 概述:电脑时间走时 ...
- IO流(1)
IO流(1) 目录 IO流(1) 文件 创建文件 获取文件信息 目录的操作和文件删除 文件 文件流 文件在程序中以流的形式来操作 输入流:数据从数据源(文件)到程序(内存)的路径 输出流:数据从程序( ...
- redis注册成windows服务步骤
1.cmd命令切换到redis的安装目录 2.执行如下命令,将redis注册成为windows的服务 redis-server --service-install redis.windows.conf ...
- vxlan结合iptables-snat实现内网服务器公网访问
如上图,有这样一种场景,我们经常遇到,局域网内有两台服务器,Server 1和Server 2,Server 1可以通通网,Server 2只能通内网,无法直接访问公网 现在想Server 2能访问到 ...
- 7.mysql索引失效
失效的七字口诀: 模型数空运最快 模:模糊查询以%开始索引失效: 型:数据类型转换 函数:函数的索引 空:索引列为空不走索引, 运:对索引列进行加减乘除会失效 最:不按聚合索引的最左匹配会 ...