没错,这几个问题都是我的一个朋友遇到的。
最近项目有个excel上传解析的功能,朋友很轻松的选择了POI,demo如下:
@PostMapping("/file/upload")
public ResponseModel fileUpload(@RequestParam("file") MultipartFile file){
try {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
XSSFRow xssfRow = xssfWorkbook.getSheetAt(0).getRow(3);
System.out.println(xssfRow.toString());
System.out.println(xssfRow.getCell(1).getRawValue());
System.out.println(xssfRow.getCell(3).toString());
} catch (IOException e) {
e.printStackTrace();
}
return ResponseModel.ok(file.getOriginalFilename());}第一个问题,异步处理文件,选择使用MQ,emmm,文件传输不能正常接收,解决这个问题倒不是很难
//传输方
String str = Base64.encode(file.getBytes())))
//接收方
new ByteArrayInputStream(Base64.decode(str))第二个问题,突然,他觉得他不想用MQ,决定使用@Async注解,不出意外,file向下传递时,报错了,找不到文件
这个么,根据我的观察,个人观点如下,接口调用返回后,会有线程删除tomcat中的上传文件缓存,异步非阻塞处理的情况,存在文件已经删除的情况,and 此处若不设置缓存路径,有个linux删除默认缓存路径的情况
设置文件路径server.tomcat.basedir=/temp,linux要考虑启动用户是否有路径操作权限
再有就是说linux会删临时路径,这个,先暂存下
这个问题的解决方式我推荐他采用上面的byte[]方式传输,他采用了直接传输流。
第三个问题,异步处理中还有个需求是要生成一份新的excel并调用上传接口,emmm,此处,盆友又new了一个file,此处我就觉得应该不用再生成文件了,这就两回了。google到一个解决方案,依然ByteArrayInputStream
public ResponseModel fileUploadTest(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, Base64DecodingException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", new ByteArrayResource(file.getBytes()){
@Override
public String getFilename() {
return file.getOriginalFilename();
} });
System.out.println(new String(file.getBytes()));
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param,headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8080/file/upload", httpEntity, String.class);
return ResponseModel.ok(responseEntity.getBody());
}大功告成
第四个问题,POI中获取Cell的值时,朋友只想要String类型,这么直接cell.toString()好了。