在application-prod中的配置
在application-local中的配置
上传
@PostMapping("uploadDemand/{id}")
@ApiOperation("报价单上传文件")
public String uploadDemand(@RequestParam("file") MultipartFile file,@PathVariable String id) {
// 获取原始名字
String fileName = file.getOriginalFilename();
// 获取后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
Integer fileType = null;
if (suffixName.toLowerCase().equals(".xls") || suffixName.toLowerCase().equals(".xlsx")){
fileType = 0;
}
if (suffixName.toLowerCase().equals(".pdf")) {
fileType = 1;
}
// 文件保存路径
String filePath = uploadFilePath;
// 文件重命名,防止重复
String fileNamesPath = filePath + UUID.randomUUID() + fileName;
// 文件对象
File dest = new File(fileNamesPath);
// 判断路径是否存在,如果不存在则创建
if(!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
// 保存到服务器中
file.transferTo(dest);
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
}
return "上传失败";
}
下载
@GetMapping("/downloadTemplate")
@ApiOperation("下载")
public void downloadOfferDemandFile(HttpServletResponse response,@RequestParam(value="fileName") String fileName,@RequestParam(value="filePath") String filePath){
StringBuilder filePathAddres = new StringBuilder(); // 文件下载地址
filePathAddres.append(filePath);
File file = new File(filePathAddres.toString());
try {
FileUtils.downloadFile(file,fileName,response);
} catch (IOException e) {
e.printStackTrace();
}
}
FileUtils类
/**
* 文件下载
*
* @param file
* 创建的文件对象 new File()
* @param response
* HttpServletResponse响应
* @param fileName
* 指定下载文件的名称
* @throws IOException
* 当文件不存在或者创建文件流时 会抛此异常
*/
public static void downloadFile(File file, String fileName, HttpServletResponse response) throws IOException {
if (!file.exists()) {
throw new FileNotFoundException("file not found:" + file.getAbsolutePath());
}
BufferedInputStream bufferStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int n;
if (fileName != null) {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
// response.setHeader("Content-disposition",
// "attachment; filename=" + new String(fileName.getBytes("gb2312"), "iso-8859-1"));
}
while (-1 != (n = bufferStream.read(buffer))) {
response.getOutputStream().write(buffer, 0, n);
}
response.getOutputStream().flush();
bufferStream.close();
}