1、文件上传
public R<String> uploadFile(MultipartFile files){
LocalDate now = LocalDate.now();
int month = now.getMonthValue();
int year = now.getYear();
int day = now.getDayOfMonth();
String s = UUID.randomUUID().toString().replace("-","");
String filename = s+files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
String returnFilename = year+"-"+month+"-"+day+"-"+filename;
String filePath = uploadDir+"\\"+year+"\\"+month+"\\"+"\\"+day+"\\"+filename;
File file = new File(filePath);
if (!file.exists()){
file.mkdirs();
}
try {
files.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
return R.success(returnFilename);
}
2、文件下载
outputStream.write()
outputStream.print()
都可以将后端的数据响应的前端,但是仔细对比是有区别的,需要根据实际使用进行区分。
@GetMapping("/download")
public void downloadFile(String name, HttpServletResponse response) throws IOException {
String[] filename = name.split("-");
String filePath = uploadDir+"/"+filename[0]+"/"+filename[1]+"/"+filename[2]+"/"+filename[3];
File file = new File(filePath);
if (file.exists()){
byte[] bytes = new byte[1024];
int read = 0;
ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fis = new FileInputStream(file);
response.setContentType("image/jpg");
try {
while ((read = fis.read(bytes)) != -1){
outputStream.write(bytes,0,read);
outputStream.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
outputStream.close();
fis.close();
}
}else{
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("<h1>文件不存在</h1>");
response.setStatus(203);
}
}