zoukankan      html  css  js  c++  java
  • mvc文件上传和下载

    文件上传

      导入依赖:

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.2</version>
    </dependency>
    
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>
    View Code

      spring-mvc文件配置:  

    <!--文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--文件上传的字符集-->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!--文件上传的总大小-->
        <property name="maxUploadSize" value="5000000000"></property>
        <!--单个文件的大小-->
        <property name="maxUploadSizePerFile" value="5000000"></property>
    </bean>
    View Code

      控制器(单文件)

    /*单文件上传*/
    @RequestMapping("/fileUpload")
    public String fileUpdate(MultipartFile upload ,HttpSession session) throws IOException {
        //获取绝对路径
        String realPath = session.getServletContext().getRealPath("/upload");
        //获取文件上传提交的文件名
        String filename = upload.getOriginalFilename();
        //组合路径+上传操作
        upload.transferTo(new File(realPath,filename));
        return "index";
    }
    View Code

      控制器(多文件)

    /*多文件上传*/
    @RequestMapping("/fileUploads")
    public String fileUpdates(@RequestParam  MultipartFile[] upload ,HttpSession session) throws IOException {
        //获取绝对路径
        String realPath = session.getServletContext().getRealPath("/upload");
        for (MultipartFile item:upload){
            //获取文件上传提交的文件名
            String filename = item.getOriginalFilename();
            //组合路径+上传操作
            item.transferTo(new File(realPath,filename));
        }
        return "index";
    }
    View Code

    文件下载

    /*文件下载*/
    @RequestMapping("/download")
    public ResponseEntity<byte[]> dowload(HttpSession session) throws Exception {
        //获取绝对路径
        String realPath = session.getServletContext().getRealPath("/upload");
        //组装路径转换为file对象
        File file=new File(realPath,"新建文本文档.txt");
        //设置头 控制浏览器下载对应文件
        HttpHeaders headers=new HttpHeaders();
        headers.setContentDispositionFormData("attachment",new String("新建文本文档.txt".getBytes("UTF-8"),"ISO-8859-1"));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    
    }
    View Code
  • 相关阅读:
    dubbo 学习
    JSTL 实现 为Select赋多个值
    Spring MVC 单元测试Demo
    IDEA git commit push revert
    高并发处理
    Redis Expire TTL命令
    Redis 原子操作INCR
    Redis 安装
    慢日志查询
    angularJs 处理多选框(checkbox)
  • 原文地址:https://www.cnblogs.com/wnwn/p/11834328.html
Copyright © 2011-2022 走看看