SpringMVC实现文件上传和下载功能

文件下载

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文。具体步骤如下:

  1. 获取下载文件的位置;
  2. 创建流,读取文件;
  3. 设置响应信息,包括响应头,响应体以及响应码;
  4. 返回ResponseEntity对象
@Controller
@ResponseBody
public class UpAndDownController {

    @RequestMapping("/test/down")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
        /**
         * 1. 获取文件的地址
         */
        // 获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        // 获取服务器的中文件的真实路径
        String path = servletContext.getRealPath("img");
        System.out.println("path: " + path);  // path: D:\IdeaProject\springmvc_ResponseBody_RequestBody\target\springmvc-1.0-SNAPSHOT\img
        String realPath = path + File.separator + "1.jpg";  // File.separator表示拼接符 “/” 或者“\”,方便拼接不会出错
        System.out.println("realPath: " + realPath);  // realPath: D:\IdeaProject\springmvc_ResponseBody_RequestBody\target\springmvc-1.0-SNAPSHOT\img\1.jpg

        /**
         * 2. 创建流,读取文件
         */
        // 创建输入流
        FileInputStream is = new FileInputStream(realPath);
        // 创建字节数组
        byte[] bytes = new byte[is.available()];  // is.available: 返回从此输入流中可以读取(或跳过)的剩余字节数的估计值
        // 将流读到字节数组中
        is.read(bytes);

        /**
         * 3. 设置响应信息,包括响应头,响应体以及响应码
         */
        // 创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        // 设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        // 设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        // 创建ResResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        // 关闭输入流
        is.close();
        return responseEntity;
    }
}

文件上传

 文件上传要求form表单的请求方式必须为post, 并且添加属性enctype=“multipart/form-data”。SpringMVC中上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。文件上传步骤如下:

  1. 添加依赖
  <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
  dependency>
  1. 在SpringMVC的配置文件中添加配置
 
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">bean>

前端代码

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>indextitle>
head>
<body>
<form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
    头像: <input type="file" name="photo"><br>
    <input type="submit" value="上传文件">
form>
body>
html>

后端代码

@RequestMapping("/test/up")
    public String testUp(MultipartFile photo, HttpSession httpSession) throws IOException{
        /**
         * 1. 获取文件的名称
         */
        // 获取上传文件的名称
        String filename = photo.getOriginalFilename();
        String hzName = filename.substring(filename.lastIndexOf("."));  // 得到后缀名
        System.out.println(hzName);  // .jpg
        System.out.println(UUID.randomUUID());
        filename = UUID.randomUUID().toString() + hzName;

        /**
         * 2. 创建文件的存储位置
         */
        // 获取服务器中photo目录的路径
        ServletContext servletContext = httpSession.getServletContext();
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);
        if(!file.exists()) file.mkdir();
        String finalPath = photoPath + File.separator + filename;

        /**
         * 3. 文件上传
         */
        // 实现上传功能
        photo.transferTo(new File(finalPath));
        return "success";
    }

你可能感兴趣的:(#,SpringMVC系列,#,SpringMVC,后端,Java,ResponseEntity,文件上传下载)