摘要:
MultipartFile工具类:
- MultipartFile是SpringMVC提供简化上传操作的工具类。
- 在不使用框架之前,都是使用原生的HttpServletRequest来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为File类,非常麻烦。使用了MultipartFile工具类之后,我们对文件上传的操作就简便许多了。
- 以下是MultipartFile工具类全部的接口方法。
方法名 返回值 作用 getContentType() String 在取文件MIME类型 getlnputStream() InputStream 获取文件流 getName() String 获取 form 表单中文件组件的名字 getOriginalFilename() String 获取上传文件件的原名 getSize() long 获取文件的大小,单位为byte isEmpty() boolean 是否为空 transferTo(File dest) void 将数据保存到一个目标文件中
1.定义一个枚举类
用来遍历excel每一列
java
package com.amarsoft.lease.commerce.constant;
public enum CmceWarrantyInfoColumnEnum {
LEASEHOLD_NO(0, "租赁物编号", "leaseholdNo"),
INSURANCE_COMPANY(1, "保险公司", "insuranceCompany"),
SLIP_NO(2, "保单号", "slipNo"),
INSURE_START_DATE(3, "保险起始日", "insureStartDate"),
INSURE_END_DATE(4, "保险到期日", "insureEndDate"),
IS_SURRENDER(5, "是否为退保单", "isSurrender");
private int columnNum;
private String columnName;
private String columnKey;
CmceWarrantyInfoColumnEnum(int columnNum, String columnName, String columnKey) {
this.columnNum = columnNum;
this.columnName = columnName;
this.columnKey = columnKey;
}
public int getColumnNum() {
return columnNum;
}
public void setColumnNum(int columnNum) {
this.columnNum = columnNum;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getColumnKey() {
return columnKey;
}
public void setColumnKey(String columnKey) {
this.columnKey = columnKey;
}
/**
* 获取列名
* @param columnNum
* @return
*/
public static CmceWarrantyInfoColumnEnum getByColumnNum(int columnNum) {
CmceWarrantyInfoColumnEnum[] columnEnums = CmceWarrantyInfoColumnEnum.values();
for (CmceWarrantyInfoColumnEnum columnEnum : columnEnums) {
if(columnEnum.getColumnNum() == columnNum) return columnEnum;
}
return null;
}
}
2.定义接口
2.1:如果接入的接口是HttpServletRequest
- // 转型为MultipartHttpRequest:
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- // 获得文件:
- MultipartFile file = multipartRequest.getFile(" file ");
- // 获得文件名:
- String filename = file.getOriginalFilename();
- // 获得输入流:
- InputStream input = file.getInputStream();
- // 写入文件
- File source = new File(localfileName.toString());
- multipartFile.transferTo(source);
2.2:直接使用 MultipartHttpServletRequest
java
@PostMapping("/uploadInsureInfo")
@Transactional
public ResultResponse<T> uploadInsureInfo(MultipartHttpServletRequest request) {
List<MultipartFile> files = request.getFiles("file");
MultipartFile file = null;
InputStream inputStream = null;
Date date = new Date();
for (int i = 0; i < files.size(); i++) {
file = files.get(i);
if (!file.isEmpty()) {
try {
inputStream = file.getInputStream();//路劲
Workbook workbook = ExcelUtils.openWorkbook(inputStream);
Sheet sheet = workbook.cloneSheet(0);
Row firstRow = sheet.getRow(0);//获取每一行的结果
if (Objects.isNull(firstRow)) {
return ResultResponse.error("导入数据为空或模板不正确, 请检查文件重新上传");
}
//获取总行数、总列数
int rowSum = sheet.getLastRowNum() + 1;
int columnSum = firstRow.getLastCellNum() + 1;
//校验列名是否正确
for (int k = 0; k < 6; k++) {
Cell name = firstRow.getCell(k);
ValueObject nameValueObject = Objects.isNull(name) ? ValueObject.valueOf(null) : new ValueObject(ExcelCellHelper.getCellValue(name));
String strName = nameValueObject.strValue();
if (strName.endsWith("*")) {
strName = strName.substring(0, strName.length() - 1);
}
if (!Objects.requireNonNull(CmceWarrantyInfoColumnEnum.getByColumnNum(k)).getColumnName().equals(strName)) {
return ResultResponse.error("导入数据为空或模板不正确, 请检查文件重新上传");
}
}
//校验每一行结果是否正确
a:
for (int i1 = 1; i1 < rowSum; i1++) {
/**
* getRow 获取行 getCell 获取列
*/
Row currentRow = sheet.getRow(i1);
if (Objects.isNull(currentRow)) continue;
CmceWarrantyInfoPO cmceWarrantyInfoPO = new CmceWarrantyInfoPO();//创建每一行落库的保单数据
Map<String, Object> cellColumnMap = new HashedMap();//用来存储遍历每一个字段的值
for (int j = 0; j < columnSum; j++) {
CmceWarrantyInfoColumnEnum templateColumnEnum = CmceWarrantyInfoColumnEnum.getByColumnNum(j);
if (Objects.isNull(templateColumnEnum)) continue;
Cell cell = currentRow.getCell(j);
//每列每行内容值
ValueObject cellValueObject = Objects.isNull(cell) ? ValueObject.valueOf(null) : new ValueObject(ExcelCellHelper.getCellValue(cell));
String cellValueStr = StringUtils.isNotBlank(cellValueObject.strValue()) ? cellValueObject.strValue().trim() : null;
//校验有无数据* firstRow(第一行结果)
Cell name = firstRow.getCell(j);
ValueObject nameValueObject = Objects.isNull(name) ? ValueObject.valueOf(null) : new ValueObject(ExcelCellHelper.getCellValue(name));
String strName = nameValueObject.strValue();
if (strName.endsWith("*") && StringUtils.isBlank(cellValueStr) && !"是否为退保单*".equals(strName)) {
return ResultResponse.error("第【"+i1+1+"】行,【"+strName+"】未录入!");
}
if (Objects.isNull(cellValueObject) && j == 0) continue a;
//每一列每一行的数据对应保存
SimpleDateFormat sip = new SimpleDateFormat("yyyy-MM-dd");
switch (templateColumnEnum){
case LEASEHOLD_NO:
if (StringUtils.isBlank(cellValueStr)) continue;
String sql = "SELECT * FROM ARTL_LEASEHOLD AL \n" +
"inner join PROJ_RELATION PR on PR.PROJECT_RELA_ID = AL.LEASEHOLD_ID\n" +
"left join proj_project pp on PR.PROJECT_APPLY_ID = PP.PROJECT_APPLY_ID \n" +
"WHERE al.LEASEHOLD_NO =:leaseholdNo AND al.EFFECT_STATUS ='Y' AND al.IS_VALID = 'Y' \n" +
"AND pp.PROJECT_STATUS in('630_setting','635_settlewaitsign','640_settlesigning','645_settletowrite','650_settled')";
Integer count = dataAccessor.selectCount(sql, "leaseholdNo", cellValueStr);
if(count>0){
cellColumnMap.put(templateColumnEnum.getColumnKey(),cellValueStr);
}else{
return ResultResponse.error("第【"+i1+1+"】行,租赁物编号无法匹配!");
}
break;
case INSURANCE_COMPANY:
if (StringUtils.isBlank(cellValueStr)) continue;
cellColumnMap.put(templateColumnEnum.getColumnKey(),cellValueStr);//保险公司
break;
case SLIP_NO:
if (StringUtils.isBlank(cellValueStr)) continue;
cellColumnMap.put(templateColumnEnum.getColumnKey(), cellValueObject.strValue());
break;
case INSURE_START_DATE:
if (StringUtils.isBlank(cellValueStr)) continue;
Date parse = sip.parse(cellValueStr);
cellColumnMap.put(templateColumnEnum.getColumnKey(), parse);
break;
case INSURE_END_DATE:
if (StringUtils.isBlank(cellValueStr)) continue;
Date parse2 = sip.parse(cellValueStr);
cellColumnMap.put(templateColumnEnum.getColumnKey(), parse2);
break;
case IS_SURRENDER:
if (StringUtils.isBlank(cellValueStr)) continue;
cellColumnMap.put(templateColumnEnum.getColumnKey(),cellValueStr);
break;
default:
continue;
}
}
if(cellColumnMap.size()>0 && cellColumnMap!=null){
BeanKit.copyProperties(cellColumnMap,cmceWarrantyInfoPO);
String leaseholdNo = cellColumnMap.get("leaseholdNo").toString();
String projectId = dataAccessor.selectOne(String.class, "SELECT pp.PROJECT_ID FROM ARTL_LEASEHOLD al \n" +
"LEFT JOIN PROJ_RELATION PR ON PR.PROJECT_RELA_ID = AL.LEASEHOLD_ID\n" +
"LEFT JOIN PROJ_PROJECT PP ON PP.PROJECT_APPLY_ID = PR.PROJECT_APPLY_ID\n" +
"WHERE al.LEASEHOLD_NO =:leaseholdNo AND al.EFFECT_STATUS ='Y' AND pp.PROJECT_EFFECT_STATUS = 'Y' AND al.IS_VALID = 'Y'", "leaseholdNo", leaseholdNo);
cmceWarrantyInfoPO.setProjectId(projectId);
//是否退保单
String isSurrender = Objects.isNull(cellColumnMap.get("isSurrender"))? "N":cellColumnMap.get("isSurrender").toString();
cmceWarrantyInfoPO.setIsSurrender(isSurrender);
dataAccessor.save(cmceWarrantyInfoPO);
//险到期日>当前日期的租赁物的投保状态更新为"已投保"
boolean after = DateKit.isAfter(date, cmceWarrantyInfoPO.getInsureEndDate());
if(after){
String sql ="SELECT ci.* FROM PROJ_PROJECT PP \n" +
"LEFT JOIN CMCE_INSURE ci ON PP.PROJECT_ID = ci.PROJECT_ID AND ci.PROJECT_APPLY_ID=pp.PROJECT_APPLY_ID \n" +
"WHERE pp.PROJECT_EFFECT_STATUS = 'Y'\n" +
"AND ci.PROJECT_ID =:projectId";
List<CmceInsurePO> cmceInsurePOS = dataAccessor.selectList(CmceInsurePO.class, sql, "projectId", projectId);
cmceInsurePOS.stream().forEach(cmceInsurePO -> {
cmceInsurePO.setInsureStatus("finishInsure");
dataAccessor.update(cmceInsurePO);
});
}
cellColumnMap.clear();
}
}
} catch (Exception e) {
return ResultResponse.error("系统异常"+e.getMessage());
} finally {
IOKit.close(inputStream);
}
}
}
return ResultResponse.success("导入成功");
}
3.文件下载
java
@RestController
@Slf4j
public class FileController {
@GetMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "boss.jpg";// 文件名
if (fileName != null) {
//设置文件路径
File file = new File("f:/upload/boss.jpg");
//File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
byte[] buffer = new byte[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);
}
return "下载成功";
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return "下载失败";
}
}