文章目录提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 一、文件上传的准备工作
- 1.1导入依赖
- 1.2 web.xml配置
- 2.3 SpringMVC.xml 配置
- 二、文件上传
- 2.1.页面
- 2.2 controller
- 二、文件下载
- 2.1.页面
- 2.2 controller
1.2 web.xml配置org.springframework spring-webmvc 5.3.15 ch.qos.logback logback-classic 1.2.10 javax.servlet javax.servlet-api 4.0.1 provided org.thymeleaf thymeleaf-spring5 3.0.14.RELEASE commons-fileupload commons-fileupload 1.3.1
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:SpringMVC.xml
1
SpringMVC
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceResponseEncoding
true
characterEncodingFilter
/*
hiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
hiddenHttpMethodFilter
/*
2.3 SpringMVC.xml 配置
text/html
application/json
二、文件上传
2.1.页面
2.2 controller
@PostMapping("/fileUpload")
public String testFileUpload(MultipartFile file,HttpSession session) throws IOException {
//获取上传的文件名
String filename = file.getOriginalFilename();
System.out.println(filename);
//获取文件后缀名
String suffixFilName = filename.substring(filename.lastIndexOf("."));
//用UUID和文件后缀名作为新的文件名,防止文件名重复问题
filename= UUID.randomUUID().toString()+suffixFilName;
System.out.println(filename);
//判断是什么类型的文件,决定放在那个文件夹里
String filePath=null;
if (filename.contains("jpg")){
filePath="/static/img";
}else if (filename.contains("mp4")){
filePath="/static/mp4";
}
System.out.println(filePath);
//获取服务器中存放文件夹的全路径
ServletContext servletContext = session.getServletContext();
String realPath = servletContext.getRealPath(filePath);
System.out.println(realPath);
//判断存放文件夹是否存在,不存在就创建
File realfile = new File(realPath);
if (!realfile.exists()){
realfile.mkdir();
}
//拼接存在文件夹全路径和文件名,为文件全路径
filePath=realPath+ File.separator +filename;
System.out.println(filePath);
//实现上传功能
file.transferTo(new File(filePath));
return "success";
}
根据文件的类型上传到不同的文件夹中,若初次上传则创建对应的文件夹。
二、文件下载 2.1.页面vue.js文件下载2.2 controller
1.jpg文件下载
@RequestMapping("/fileDown/{fileName}")
public ResponseEntity testResponseEntity(@PathVariable("fileName") String fileName, HttpSession session) throws
IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String filePath=null;
if (fileName.contains("jpg")){
filePath="/static/img/"+fileName;
}else if (fileName.endsWith("pm4")){
filePath="/static/mp4/"+fileName;
}
String realPath = servletContext.getRealPath(filePath);
System.out.println(realPath);
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename="+fileName);
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity responseEntity = new ResponseEntity<>(bytes, headers,
statusCode);
//关闭输入流
is.close();
return responseEntity;
}
根据文件的类型到不同的文件夹中下载。



