springboot文件上传下载
public boolean upload(MultipartFile file, String newFileName) throws Exception {
if (file.isEmpty()) {
return false;
}
// 获取文件名
String fileName = file.getOriginalFilename();
log.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("文件的后缀名为:" + suffixName);
// 设置文件存储路径
String filePath = "D:\\MyDownloads";
String path = filePath + File.separator + newFileName;
File dest = new File(path);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹
}
try {
file.transferTo(dest);// 文件写入
} catch (Exception e) {
throw new BusinessException("文件上传失败!");
}
return true;
}
public void download(String fileName, String savename, HttpServletResponse response) {
if (fileName != null) {
//设置文件路径
File file = new File("D:\\MyDownloads\\a.txt");
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
response.setHeader("Context-Type", "application/xmsdownload");
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
String s = new String(buffer, 0, i);
System.out.println(s);
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("下载成功");
} catch (Exception e) {
e.printStackTrace();
} finally {//关闭连接
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
System.out.println("下载失败");
}