文件上传和下载

文件下载

使用 ResponseEntity 实现下载文件的功能

@RequestMapping("/download")
public ResponseEntity<byte[]> downloadResponseEntity (HttpSession session) throws IOException {
    ServletContext servletContext = session.getServletContext();
    String Path = servletContext.getRealPath("/static/hello.js");

    InputStream is = new FileInputStream(Path);
    byte[] bytes = new byte[is.available()];
    is.read(bytes);

    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add("Content-Disposition", "attachment;filename=hello.js");
    HttpStatus statusCode = HttpStatus.OK;

    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    is.close();

    return responseEntity;
}

文件上传

文件上传要求 form 表单的请求方式必须为 post,并且添加属性enctype=“multipart/form-data”

SpringMVC 中将上传的文件封装到 MultipartFile 对象中,通过此对象可以获取文件相关信息

步骤:

  • 添加依赖:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
  • 在 SpringMVC 的配置文件中添加配置
<!-- 必须通过文件解析器的解析才能将文件转换为 MultipartFile 对象 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
  • 表单
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
  • controller
@PostMapping("/upload")
public String upload(HttpSession session, MultipartFile file) throws IOException {
    String fileName = file.getOriginalFilename();
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    fileName = UUID.randomUUID() + suffixName;

    ServletContext servletContext = session.getServletContext();
    String realPath = servletContext.getRealPath("/uploads");

    File path = new File(realPath);
    if (!path.exists()){
        path.mkdir();
    }

    String finalName = realPath + File.separator + fileName;
    file.transferTo(new File(finalName));

    return "success";
}