springMVC中的文件上传和下载

发布于:2024-07-01 ⋅ 阅读:(15) ⋅ 点赞:(0)

10、文件上传和下载

10.1文件下载

ResponseEntity用于控制器方法的返回值的类型,该控制器方法的返回值就是响应到浏览器响应报文使用ResponseEntity实现下载文件的功能

	@RequestMapping("/test/download")
    public ResponseEntity<byte[]> testDownload(HttpSession session) throws IOException {
        // 首先获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        // 获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("img");
        realPath = realPath + File.separator + "1.png";
        // 创建输入流
        InputStream inputStream = new FileInputStream(realPath);
        // 创建字节数组
        byte[] bytes = new byte[inputStream.available()];
        // 将输入流写入字节数组
        inputStream.read(bytes);
        // 设置响应头
        MultiValueMap<String, String> httpHeaders = new HttpHeaders();
        // 设置文件下载信息和文件名称
        httpHeaders.add("Content-Disposition", "attachment;filename=1.png");
        // 设置状态码
        HttpStatus httpStatus = HttpStatus.OK;
        // 创建 ResponseEntity 对象并返回
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, httpStatus);
        // 关闭输入流
        inputStream.close();
        return responseEntity;
    }

10.2文件上传

  1. 引入依赖
        <!--        // 文件上传-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>
  1. 文件上传的要求:
    1. form表单的请求方式必须为post
    2. form表单必须设置属性enctype=“multipart/form-data”
        <form method="post" th:action="@{/test/upload}" enctype="multipart/form-data">
            头像:<input type="file" name="photo"><br>
            <input type="submit" value="上传">
        </form>
    

    我这里用的是thymeleaf模板,如果你没有使用这个,直接用form表单也是可以的

    服务器端的java代码

    @RequestMapping("/test/upload")
        public String testUpload(MultipartFile photo, HttpSession session) throws IOException {
            // 获取上传文件的名称
            String originalFilename = photo.getOriginalFilename();
            // 获取上传文件名的后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 获取uuid
            String uuid = UUID.randomUUID().toString();
            // 拼接一个新的文件名
            originalFilename = uuid + suffix;
            // 获取服务器中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 + originalFilename;
            photo.transferTo(new File(finalPath));
            return "success";
    
        }
    

.transferTo(new File(finalPath));
return “success”;

   }

**上面使用了UUID,UUID你可以直接理解成(UUID 只是一个值,您可以放心地将其视为唯一值。碰撞的风险是如此之低,以至于您可以合理地选择完全忽略它。)使用UUID的作用也就是生成一个不会重复的文件名,因为对于服务器而言,可能有很多很多的文件上传功能,如何都是一样的名字,那么就会对文件进行覆盖,这样,先上传的文件就会丢失**