springmvc中文件的上传和下载

文件的下载

  1. 导入springmvc依赖

  2. 将tomcat的jar包加入model的依赖中

  3. 下载代码

    @RequestMapping("/fileDownload")
    public String fileDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获得当前项目路径下的下载文件(真实开发中文件名肯定是从数据中读取的)
        String realPath = request.getServletContext().getRealPath("/file/20181129204254948.png");
        File file = new File(realPath);
        String fileName = file.getName();
        // 设置响应头 content-disposition: 就是设置文件下载的打开方式,默认会在网页上打开,
        // 设置attachment;filename= 就是为了以下载方式来打开文件
        // "UTF-8"设置如果文件名有中文就不会乱码
        response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
        InputStream in = new FileInputStream(realPath);
        int len = 0;
        byte[] buffer = new byte[1024];
        OutputStream out = response.getOutputStream();
        while ((len=in.read(buffer))>0){
            out.write(buffer,0,len);
        }
        in.close();
        return null;
    }
    /**
         * 基于spring ResponseEntity的文件下载 不支持缓冲区
         * ResponseEntity 可以同时定制文件的响应内容,响应头, 响应状态码
         */
    @RequestMapping("/responseBody")
    public ResponseEntity<String> responseBody(){
        String body = "Hello wuJiao";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Set-Cookie","name=jqc");
        return new ResponseEntity<String>(body,httpHeaders, HttpStatus.OK);
    }
    

文件的上传

  1. 导入springmvc依赖和上传特有依赖

    <!--1.加入依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    <!--基于Jakarta commons-fileupload的上传支持-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    
  2. 将jar包手动加入到tomcat容器中

  3. 注入文件上传解析器

    <!--基于CommonsMultipartResolver的文件上传解析器-->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" name="multipartResolver">
        <property name="maxUploadSize" value="#{1024*1024*10}"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
    
  4. 上传form表单要加上enctype="multipart/form-data",选择多文件input属性加multiple

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>$Title$</title>
      </head>
      <body>
       
      <a href="${pageContext.request.contextPath}/download">文件下载</a>
    
       <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload01" method="post">
         <p>文件描述:<input type="text" name="desc" /></p>
         <p>文件:<input type="file" name="myfile" multiple accept="image/*"/></p>
         <p><input type="submit" value="上传单个文件"></p>
       </form>
       <hr>
      <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload03" method="post">
        <p>文件描述:<input type="text" name="desc" /></p>
        <p>文件:<input type="file" name="myfile" multiple accept="image/*"/></p>
        <p><input type="submit" value="上传多个文件"></p>
      </form>
    
      </body>
    </html>
    
  5. 后台代码

     /**
         *基于springmvc MultiPartResolver文件上传
         * @param desc
         * @param myFile
         * @param model
         * @return
         * @throws IOException
         */
    @PostMapping("/upload01")
    public String upload01(String desc,@RequestParam MultipartFile myFile, Model model) throws IOException {
        String path = "D:\\test\\"+ myFile.getOriginalFilename();
        File file = new File(path);
        //上传文件
        myFile.transferTo(file);
        model.addAttribute("filename",myFile.getOriginalFilename());
        return "success";
    }
    
    /**
         * 多文件上传
         * @param desc
         * @param myFile
         * @return
         * @throws IOException
         */
    @PostMapping("/upload02")
    public String upload02(String desc,@RequestParam MultipartFile[] myFile) throws  IOException {
        for (MultipartFile multipartFile : myFile) {
            String path = "D:\\test\\"+multipartFile.getOriginalFilename();
            File file = new File(path);
            //上传文件
            multipartFile.transferTo(file);
        }
        return "success";
    }
    
posted @ 2021-03-21 21:51  阿灿呀  阅读(62)  评论(0)    收藏  举报