SpringMVC实现上传和下载

这个东西长时间不用就很容易忘记,记录一下SpringMVC实现上传和下载功能。

SpringMVC文件上传下载

文件下载

/*可能会在接收图片的时候会丢失后缀,所有要加上:.+*/
   @RequestMapping("/download/{filename:.+}")
   public ResponseEntity download(@PathVariable String filename, HttpSession session) throws Exception {

       //1.获取文件路径
       String realPath = session.getServletContext().getRealPath("/download/" + filename);
       System.out.println(realPath);

       //2.把程序读到文件中
       FileInputStream inputStream = new FileInputStream(realPath);
       byte[] bytes = new byte[inputStream.available()];
       inputStream.read(bytes);

       //3.创建响应头
       HttpHeaders httpHeaders = new HttpHeaders();
       //注意,如果附件有中文的需要对附件进行编码
       filename = URLEncoder.encode(filename,"UTF-8");
       httpHeaders.add("Content-Disposition", "attchement;filename=" + filename);


       //4.下载
       ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(bytes,httpHeaders, HttpStatus.OK);

       return entity;
  }

文件上传

  1. 导入依赖

    <!--文件上传
       commons-io不用导,导入commons-fileupload后maven会自动你导入
    -->
    <dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.3.2</version>
    </dependency>
  2. 编写SpringMVC配置文件

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <!--编码-->
       <property name="defaultEncoding" value="UTF-8"/>
       <!--最大上传-->
       <property name="maxUploadSize" value="10240000"/>
    </bean>
  3. 编写代码

    /*文件上传*/
    @RequestMapping("/uploadFile")
    public void uploadFile(@RequestParam("file") CommonsMultipartFile file,HttpSession session) throws IOException {
       //获取上传路径
       String realPath = session.getServletContext().getRealPath("/upload");

       //转为程序路径
       File filePath = new File(realPath);
       //文件如果不存在那么就创建一个
       if (!filePath.exists()){
           filePath.mkdir();
      }

       //确认最终的上传路径
       String filename = file.getOriginalFilename();
       //对文件名进行处理,预防名字冲突的问题

       int index = filename.lastIndexOf(".");
       String indexName = filename.substring(index);

       String uuid = UUID.randomUUID().toString();
       String replace = uuid.replace("-", "");
       String newFileName =  replace + indexName;
       System.err.println(newFileName);

       filePath = new File(filePath + "/" + newFileName);

       //上传
       file.transferTo(filePath);

    }

     

  4.  

posted @ 2020-08-12 21:57  UnXun  阅读(459)  评论(0)    收藏  举报