最近工作中,遇到了一个业务,需要将本地的excel上传到阿里云作为模板,下载模板的时候从阿里云上下载要求用流的形式。总结一下,希望能帮到别人。
上传:
@PostMapping("import")
public Result userImpoetTemplate(@RequestBody MultipartFile multipartFile) {
File resultFile = new File("选择一个和文件类型相同的文件绝对路径");
try {
String fileName = "filename";
//将MultipartFile类型 转为File
multipartFile.transferTo(resultFile);
if (resultFile != null) {
//封装了oss的上传方法,可以参考阿里云sdk
String url = fileUploadSerivice.uploadByPart(fileName + ".xlsx", resultFile);
url = url.replaceFirst("http://", "https://");
System.out.println(url);
} else {
throw new ServiceException("生成文件失败");
}
} catch (Exception e) {
throw new ServiceException("文件生成失败");
} finally {
if (resultFile.exists()) {
resultFile.delete();
}
}
return new Result();
}
下载:
@RequestMapping(value = "down", method = RequestMethod.POST)
public Result downUserTemplate(HttpServletResponse response) {
String filename = "filename.xlsx";
try {
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
response.reset();
//xslx格式必须是这个
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s", URLEncoder.encode(filename, "utf-8")));
InputStream inputStream = fileUploadSerivice.downloadFile(filename);
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return new Result();
}