下面代码只需要设置服务器文件名(getRealPath("/static/img/1.jpg"))和下载到本地的文件名("attachment;filename=1.jpg")
关于ServletContext.getRealPath()
ServletContext.getRealPath("") 获取到的是项目部署到服务器后的项目根路径。
ServletContext.getRealPath("文件名或文件夹名") 获取到的是项目部署到服务器后某文件或文件夹的路径。

String photoPath1 = servletContext.getRealPath("");
F:\JavaProject\SpringMVC\springMVC-demo04\target\springMVC-demo04\
String photoPath = servletContext.getRealPath("photo");
F:\JavaProject\SpringMVC\springMVC-demo04\target\springMVC-demo04\photo
- @RequestMapping("/testDown")
- public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
- //获取ServletContext对象
- ServletContext servletContext = session.getServletContext();
- //获取服务器中文件的真实路径
- String realPath = servletContext.getRealPath("/static/img/1.jpg");
- //创建输入流
- InputStream is = new FileInputStream(realPath);
- //创建字节数组
- //is.available()获取输入流的文件全部的字节
- byte[] bytes = new byte[is.available()];
- //将流读到字节数组中
- is.read(bytes);
- //创建HttpHeaders对象设置响应头信息
- MultiValueMap
headers = new HttpHeaders(); - //设置要下载方式以及下载文件的名字
- headers.add("Content-Disposition", "attachment;filename=1.jpg");
- //设置响应状态码
- HttpStatus statusCode = HttpStatus.OK;
- //创建ResponseEntity对象
- //bytes 响应体
- //headers响应头
- ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
- //关闭输入流
- is.close();
- return responseEntity;
- }
文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
- <form method="post" th:action="@{/testUp}" enctype="multipart/form-data">
- <input type="file" name="photo">
- <input type="submit" value="上传">
- form>
1. 添加依赖 在SpringMVC的配置文件中添加配置:
- <dependency>
- <groupId>commons-fileuploadgroupId>
- <artifactId>commons-fileuploadartifactId>
- <version>1.3.1version>
- dependency>
2. 在SpringMVC的配置文件中添加配置
必须通过文件解析器的解析才能将通过表单上传的文件转换为MultipartFile对象
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">bean>
3. 控制器方法
在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常。
关于File.separator
比如说要在temp目录下建立一个test.txt文件,在Windows下应该这么写:
File file1 = new File ("C:\tmp\test.txt");
在Linux下则是这样的:
File file2 = new File ("/tmp/test.txt");
如果要考虑跨平台,则最好是这么写:
File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");
File类有几个类似separator的静态字段,都是与系统相关的,在编程时应尽量使用。
重名问题(UUID)
先通过 substring来截取后缀名
再将uuid与后缀名结合
- @RequestMapping("/testUp")
- public String testUp(MultipartFile photo, HttpSession session) throws IOException {
- //获取上传的文件的文件名
- String fileName = photo.getOriginalFilename();
- //处理文件重名问题
- String hzName = fileName.substring(fileName.lastIndexOf("."));
- fileName = UUID.randomUUID().toString() + hzName;
- //获取服务器中photo目录的路径
- ServletContext servletContext = session.getServletContext();
- String photoPath = servletContext.getRealPath("photo");
- File file = new File(photoPath);
- if(!file.exists()){
- file.mkdir();
- }
- String finalPath = photoPath + File.separator + fileName;
- //实现上传功能
- photo.transferTo(new File(finalPath));
- return "success";
- }