需求:需要提供给客户一个 上传文件的模板,实现下载模板,用户在模板填完信息之后,可以上传文件进行核对
这里选择把模板文件放到了resources路径下templates下
代码:
@Override
public void checkListTemplate(HttpServletResponse response, HttpServletRequest request) {
//服务器存储的临时文件夹地址 wind :D:/pdfData/
String docPath = fileUploadConfig.getDocPath();
//判断文件夹是否存在
File folder = new File(docPath);
if (!folder.exists() && !folder.isDirectory()) {
folder.mkdirs();
System.out.println("创建文件夹: " + docPath);
} else {
System.out.println("文件夹已存在: " + docPath);
}
// 读取模板文件,获得InputStream输入流
ClassPathResource res = new ClassPathResource("templates/heduidandaoru.xlsx");
InputStream hFile = null;
String path = "";
try {
hFile = res.getInputStream();
//输入流转byte数组,这里使用了apache.commons.io的包
byte[] bytes = IOUtils.toByteArray(hFile);
//UUID去掉"-"做文件名,防止文件重复
String uuid = UUID.randomUUID().toString();
uuid = uuid.replaceAll("-", "");
//表格名称
String xlsxFileName = uuid + ".xlsx";
//把表格文件存到本地
FileUtils.uploadFile(bytes, docPath, xlsxFileName);
//表格全路径
String xlsxFileDoc = docPath + xlsxFileName;
//表格file文件
File file = new File(xlsxFileDoc);
//表格path全路径
path = file.getPath();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
OutputStream outputStream = null;
try {
FileInputStream inputStream = new FileInputStream(path);
int i = inputStream.available(); // 得到文件大小
byte data[] = new byte[i];
inputStream.read(data); // 读数据
inputStream.close();
response.reset();
response.resetBuffer();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
LocalDate now = LocalDate.now();
String filename = "核对单导入模板" + now;
String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
outputStream = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
outputStream.write(data); // 输出数据
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
}
//删除文件夹下文件
DeleteFileListUtils.deleteFileList(docPath);
}
InputStream转byte数组
org.apache.commons commons-io1.3.2 //输入流转byte数组 byte[] bytes = IOUtils.toByteArray(inputStream);



