Chapter 8: SpringMVC file upload and download

1. File upload and download

1. File download

Use ResponseEntity for the return value type of the controller method , and the return value of the controller method is the response message to the browser. Use ResponseEntity to realize the function of downloading files.

①Create file.html

② In the FileController.java class

Whether a file is uploaded or downloaded, it is a process of file copying. So first read through the input stream. InputStream

//文件下载
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session, @RequestParam("filename") String filename) throws IOException {
   //获取ServletContext对象
   ServletContext servletContext = session.getServletContext();
   //获取文件的路径
   String realPath = servletContext.getRealPath("/static/img/"+filename);
   //创建输入流
   InputStream is = new FileInputStream(realPath);
   //创建字节数组 is.available()所有字节数,数组的长度
   byte[] bytes = new byte[is.available()];
   //将流读到字节数组中
   is.read(bytes);
   // 创建HttpHeader响应头信息
   MultiValueMap<String, String> headers = new HttpHeaders();
   // 设置下载方式以及下载文件的名字
   headers.add("Content-Disposition", "attachment;filename="+filename);
   // 设置响应状态码
   HttpStatus statusCode = HttpStatus.OK;
   // 创建ResponseEntity对象  响应体,响应头,响应状态码
   ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
   // 关闭流
   is.close();
   return responseEntity;
}

②If only page jumping is realized, no business logic processing is performed. Inside SpringMVC.xml

<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<mvc:annotation-driven />

2. File upload

  • File upload requires a form form and is a post ,
  • Add attribute enctype="multipart/form-data", binary upload
  • SpringMVC encapsulates the uploaded file into a MultipartFile object. Get file-related information through this object.

①file.html page

<form th:action="@{/testUp}" action="post" enctype="multipart/form-data">
    头像<input type="file" name="photo"><br><br>
    <input type="submit" value="上传">
</form>

 ② Add relevant configuration

Add dependencies in pom.xml

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

Configure in springMVC.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

③File Controller controller

@RequestMapping("/testUp")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
   //获取上传的文件的文件名
   String fileName = photo.getOriginalFilename();
   //获取servletContext对象,获取photo文件夹目录
   ServletContext servletContext = session.getServletContext();
   //获取photo目录的路径
   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";
}

④ Handle the problem of duplicate names of uploaded files

Cut file name and suffix

String prefixName = fileName.substring(0,fileName.indexOf("."));
String suffixName = fileName.substring(fileName.lastIndexOf("."));

Combine by UUID

fileName = prefixName+UUID.randomUUID().toString().substring(0,8)+suffixName;

full code

 

// 文件上传
@RequestMapping("/testUp")
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
   //获取上传的文件的文件名
   String fileName = photo.getOriginalFilename();
   //重名问题,获取文件名和后缀名
   String prefixName = fileName.substring(0,fileName.indexOf("."));
   String suffixName = fileName.substring(fileName.lastIndexOf("."));
   fileName = prefixName+UUID.randomUUID().toString().substring(0,8)+suffixName;
   //获取servletContext对象,获取photo文件夹目录
   ServletContext servletContext = session.getServletContext();
   //获取photo目录的路径
   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";
}

Guess you like

Origin blog.csdn.net/jbkjhji/article/details/131068278