文件上传以前是噩梦一样的存在,觉得很少麻烦,后来仔细研究后发现通过前端传文件去调取后端接口并不是特别复杂,接下来我详细说一下通过接口的方式接收前端传过来的文件,并且解析文件中内容的方法
话不多说,开整代码
@RestController
@RequestMapping("/api/invoice")
public class InvoiceController {
private static Logger logger = LoggerUtil.getLogger();
@Autowired
private InvoiceService invoiceService;
@RequestMapping(value = "/getInvoiceInfo", method = RequestMethod.POST)
@ResponseBody
private String getInvoiceInfo(@RequestParam("file") MultipartFile file) {
logger.info("/getInvoiceInfo接口调用");
return invoiceService.getInvoiceInfo(file);
}
}
剩下的写业务层,就不多谢业务了,主要写一下怎么转换并获取内容
/**
* 将MultipartFile转换为File
* @param multiFile
* @return
*/
public File multipartFileToFile(MultipartFile multiFile) {
// 获取文件名
String fileName = multiFile.getOriginalFilename();
// 获取文件后缀(.xml)
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 若要防止生成的临时文件重复,需要在文件名后添加随机码
try {
//"tmp", ".txt"
//fileName这块可以根据自己的业务需求进行修改,我这里没有做任何处理
File file = File.createTempFile(fileName, suffix);
multiFile.transferTo(file);
return file;
} catch (Exception e) {
logger.error("MultipartFile转File失败",e);
}
return null;
}
//在业务侧写代码时记得处理掉这个临时文件
if (file!=null){
file.deleteOnExit();
}
以上代码就是将MultipartFile转换为File的相关代码
再说说怎么把txt文件内容和excel读取出来处理
上代码:读取txt
@RequestMapping(value = "/uploadFileTxt", method = RequestMethod.POST)
@ResponseBody
private AjaxResult uploadFileTxt(@RequestParam("file") MultipartFile file) throws Exception {
System.out.println("uploadFileTxt");
telephoneService.uploadFileTxt(file);
return AjaxResult.success();
}
@Override
public void uploadFileTxt(MultipartFile txtFile) {
Set txtFileSet = new HashSet<>();
String fileName = txtFile.getOriginalFilename();
try {
txtFileSet = uploadRtnMap(txtFile);
}catch (IOException e){
e.printStackTrace();
}
//业务代码
//remove(new QueryWrapper<>());
// txtMapper.deleteTxtdata();
// for(String txt:txtFileSet){
// TxtVO txtVO = new TxtVO();
// txtVO.setTelephone(txt);
// txtVO.setFilename(fileName);
// txtVO.setCreateTime(new Date());
// save(txtVO);
// }
}
public static Set uploadRtnMap(MultipartFile file) throws IOException {
InputStream is = null;
InputStreamReader isReader = null;
BufferedReader br = null;
Set phoneList = new HashSet();
try {
is = file.getInputStream();
isReader = new InputStreamReader(is, StandardCharsets.UTF_8);
br = new BufferedReader(isReader);
//循环逐行读取
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
phoneList.add(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
if (isReader != null) {
isReader.close();
}
if (br != null) {
br.close();
}
}
return phoneList;
}
读取excel
@Override
public void uploadFileExcel(MultipartFile excelFile) {
ExcelUtil util = new ExcelUtil(ExcelVO.class);
List excelList = new ArrayList<>();
try{
//excel里面的内容
excelList = util.importExcel(excelFile.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
// 业务
// excelService.saveExcel(excelList);
}
提供几个工具类给大家
ExcelVO对象
@Data
@TableName("exceldata")
public class ExcelVO {
//id
@TableId(type= IdType.AUTO)
private String id;
//手机号
@Excel(name = "手机号")
private String telephone;
//QQ号
@Excel(name = "QQ号")
private String qq;
//创建时间
private Date createTime;
}
ExcelUtil.java工具类
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RegExUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/**
* Excel相关处理
*/
public class ExcelUtil
{
private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
/**
* Excel sheet最大行数,默认65536
*/
public static final int sheetSize = 65536;
/**
* 工作表名称
*/
private String sheetName;
/**
* 导出类型(EXPORT:导出数据;IMPORT:导入模板)
*/
private Type type;
/**
* 工作薄对象
*/
private Workbook wb;
/**
* 工作表对象
*/
private Sheet sheet;
/**
* 样式列表
*/
private Map styles;
/**
* 导入导出数据列表
*/
private List list;
/**
* 注解列表
*/
private List
本来想多上传几个工具类和枚举类,但是csdn这个编辑文字一多就卡住了,只能先写这里,剩下的枚举后面有机会继续上传,大家有需要可以私信博主