一.上传
@GetMapping("upload")
public Map<String,String> upload(MultipartFile[] files){
HashMap<String, String> result = new HashMap<>();
//判断是否没有上次文件
if (files.length==0) {
result.put("message","请选择文件");
return result;
}
//判断源文件名称是否为空
String originalFilename = files[0].getOriginalFilename();
if (StringUtils.isBlank(originalFilename)) {
result.put("message","请选择文件");
return result;
}
//截取后缀名
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
String lastFilePath;
//新生成的文件名称
String newFileName = UUID.randomUUID() + suffix;
//指定目录
String folderName = File.separator + "t1" + File.separator;
//拼接完整路径
String filePath = "D:\\uplode" + folderName;
//待保存的文件绝对路径
String url=null;
//判断目录是否存在,不存在就创建
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
//创建文件输出流
FileOutputStream fileOutputStream=null;
lastFilePath= filePath+File.separator+newFileName;
try {
fileOutputStream = new FileOutputStream(lastFilePath);
//写入流
fileOutputStream.write(files[0].getBytes());
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
if (fileOutputStream !=null) {
try {
//刷新流
fileOutputStream.flush();
//关闭流
fileOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
//判断url是否为空
if (StringUtils.isBlank(lastFilePath)) {
result.put("message","图片上传失败!");
return result;
}
result.put("url",lastFilePath);
result.put("message","图片上传成功!");
return result;
}
二.下载
@GetMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response,String url) {
//源文件名称
String fileName = "th.jpg";// 文件名
if (fileName != null) {
//设置文件路径
File file = new File(url);
//File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
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) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
return "下载成功";
} 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();
}
}
}
}
}
return "下载失败";
}