SpringMVC实现上传和下载

上传和下载都是复制的过程,上传是将文件从浏览器复制到服务器中,下载是将文件从服务器复制到浏览器中。

在网页中创建下载和上传按钮:

 下载:

 @RequestMapping("/test/down")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //session:获取要下载的文件在服务器的路径;
        //servletContext.getRealPath(""):如果传入一个空字符串,表示获取当前工程在服务器中的路径
        //如果控制器方法的返回值类型是void,那么请求路径 /test/down 将会被当做视图名称进行解析

        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("img");
        realPath = realPath + File.separator + "1.jpg";

        System.out.println(realPath);
        //创建输入流
        InputStream is = new FileInputStream(realPath);//将文件字节响应浏览器
        //创建字节数组,is.available()获取输入流所对应文件的字节数,即该参数是个数字
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }

下载的返回值类型用:

ResponseEntity<byte[]>,表示响应到浏览器的完整的响应报文

上传:

@RequestMapping("/test/up")
    public String testUp(MultipartFile photo, HttpSession session) throws IOException {
        //MultipartFile:封装上传文件的对象
        //photo是上传的文件的文件名,在上传表单里定义
        //photo.transferTo(new File("img")):封装了复制过程

        //获取上传的文件的文件名
        String fileName = photo.getOriginalFilename();
        //获取上传的文件的后缀名
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        //获取uuid
        String uuid = UUID.randomUUID().toString();
        //拼接一个新的文件名
        fileName = uuid + hzName;

        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取当前工程下photo目录的真实路径
        String photoPath = servletContext.getRealPath("photo");
        //创建photoPath所对应的File对象
        File file = new File(photoPath);
        //判断file所对应目录是否存在
        if(!file.exists()){
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + fileName;
        //上传文件
        photo.transferTo(new File(finalPath));
        return "success";
    }

文件上传的要求:

        a>form表单的请求方式必须为post

        b>form表单必须设置属性enctype = "multipart/form-data"

        c>添加依赖:

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

        d>配置文件上传解析器,且解析器容器的id为固定值:

 在运行过程中,如果出现不支持 diamond 运算符的情况:

可以在添加以下属性:

737cddad5cc33c5d3d972b26264a4fff.png 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Spring MVC的文件上传下载功能,需要进行以下步骤: 1、引入Apache Commons FileUpload组件的依赖。在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> ``` 2、配置文件上传解析器。在Spring MVC的配置文件中,配置一个MultipartResolver的Bean用于处理文件上传请求。 3、创建文件上传的表单。在HTML表单中,设置enctype为"multipart/form-data",并添加一个文件选择框。 4、创建文件上传的控制器。在控制器中,使用MultipartFile参数接收上传的文件,并执行相应的操作,比如保存文件到指定位置。 5、创建文件下载的控制器。在控制器中,使用ResponseEntity<byte[]>对象来实现文件的下载,设置相应的响应头信息,如Content-Disposition和文件名。 下面是一个示例的代码,演示了如何实现文件上传下载: ``` // 文件上传的控制器 @Controller public class FileUploadController { @RequestMapping("/fileUpload") public String testFileUpload(MultipartFile photo, HttpSession session) throws IOException { String filename = photo.getOriginalFilename(); ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("photo"); File file = new File(realPath); if (!file.exists()) { file.mkdir(); } String finalPath = realPath + File.separator + filename; photo.transferTo(new File(finalPath)); return "success"; } } // 文件下载的控制器 @Controller public class FileDownloadController { @RequestMapping("/fileDownload") public ResponseEntity<byte[]> testFileDownload(HttpSession session) throws IOException { ServletContext servletContext = session.getServletContext(); String realPath = servletContext.getRealPath("static/img/a.jpg"); InputStream inputStream = new FileInputStream(realPath); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=a.jpg"); HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, status); inputStream.close(); return responseEntity; } } // 文件上传的表单 <form action="${pageContext.request.contextPath}/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="photo" multiple> <input type="submit" value="上传"/> </form> ``` 通过以上步骤,你可以在Spring MVC中实现文件的上传下载功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值