【SpringMvc】的文件上传和下载

1.文件上传
SpringMVC为文件上传提供了直接的支持,这种支持是通过即插即用的multipartResolver实现的。Spring使用Jakarta Commons FileUpload 技术实现了一个multipartResolver实现类:CommonsMultipartResolver。SpringMVC上下文中默认没有装配multipartResolver,因此默认情况下不能处理文件的上传工作。如果想使用文件上传功能,需要先在上下文中配置multipartResolver。除此之外,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。 一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,选择的文件以二进制数据发送给服务器。

  • 1.1需要导入的jar
    为了让CommonsMultipartResolver能正常工作,必须先将commons-io-1.3.2.jar、commons-fileupload-1.3.jar添加到类路径下。

  • 1.2开启文件上传,配置springmvc.xml

<!-- 配置支持文件上传类:文件上传解析器 -->
<bean id="multipartResolver"  
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
       <property name="defaultEncoding" value="utf-8" /><!-- 请求的编码格式,默认ISO-8859-1 -->  
       <property name="maxUploadSize" value="10485760" /><!-- 上传文件大小上限,单位为字节(10M) -->  
       <property name="maxInMemorySize" value="40960" /><!-- 内存中的最大值 -->  
       <!-- <property name="uploadTempDir" value="upload/image" /> --><!-- 上传文件的临时路径 -->  
</bean> 

defaultEncoding必须和用户JSP的pageEncoding属性一致,以便正确读取表单的内容。
uploadTempDir是文件上传过程所使用的临时目录,文件上传完成后,临时目录中的临时文件会被自动清除。
  • 1.3代码实现
前端upload.jsp内容:
<body>
    <form action="${pageContext.request.contextPath}/upload" method="post" 
        enctype="multipart/form-data">
        <h2>文件上传</h2>
        文件:<input type="file" name="uploadFile"/><br>
        <input type="submit" value="上传">
    </form>
</body>

这里写图片描述

//文件上传Controller
@RequestMapping(value = "upload",method=RequestMethod.POST)
public String upload(@RequestParam("uploadFile") MultipartFile uploadFile,HttpSession session){
    //@RequestParam("uploadFile") MultipartFile uploadFile:上传的文件自动绑定到MultipartFile中
    try {
        if(!uploadFile.isEmpty()){
            //获取文件名作为保存到服务器的文件名称
            String filename = uploadFile.getOriginalFilename();
            if(filename.endsWith("jpg") || filename.endsWith("gif") 
                    || filename.endsWith("png")){
                //文件名称在服务器有可能重复
                String newFileName="";
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                newFileName = sdf.format(new Date());

                Random r = new Random();

                for(int i =0 ;i<3;i++){
                    newFileName=newFileName+r.nextInt(10);
                }
                String suffix = filename.substring(filename.lastIndexOf("."));
                //前半部分路径,目录,将webRoot下一个名称为images文件夹转换成绝对路径
                String leftPath = session.getServletContext().getRealPath("/image");
                //进行路径拼接=前半部分路径+文件名称
                File file = new File(leftPath,newFileName+suffix);
                //如果目录不存在,创建目录
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                uploadFile.transferTo(file);
            }
        }
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }
    return "success";
}

springmvc会将上传文件绑定到MultipartFile对象中,MultipartFile提供了获取上传文件内容、文件名等内容,通过其transferTo()方法还可以将文件存储到硬件中,具体说明如下:
    byte[] bytes = uploadFile.getBytes();//获取文件数据
    String contentType = uploadFile.getContentType();//获取文件MIME类型,如image/pjpeg、text/plain等
    InputStream inputStream = uploadFile.getInputStream();//获取文件流
    String name = uploadFile.getName();//获取表单中文件组件的名字
    String originalFilename = uploadFile.getOriginalFilename();//获取上传文件的原名
    long size = uploadFile.getSize();//获取文件的字节大小,单位为byte
    boolean flag = uploadFile.isEmpty();//是否有上传文件
    uploadFile.transferTo(File dest);//可以使用该文件将上传文件保存到一个目标文件中

实现效果:
这里写图片描述

  • 1.4多文件上传
前端upload.jsp内容:
<form action="${pageContext.request.contextPath}/uploadMore" method="post" 
    enctype="multipart/form-data">
    <h2>多文件上传</h2>
    文件:<input type="file" name="uploadFile"/><br>
    文件:<input type="file" name="uploadFile"/><br>
    文件:<input type="file" name="uploadFile"/><br>
    <input type="submit" value="上传">
</form>

这里写图片描述

//多文件上传Controller
@RequestMapping(value = "uploadMore",method=RequestMethod.POST)
public String uploadMore(@RequestParam MultipartFile[] uploadFile,HttpSession session){
    try {
        for(MultipartFile item : uploadFile){
            if(item.getSize()>0){
                //获取文件名作为保存到服务器的文件名称
                String filename = item.getOriginalFilename();
                if(filename.endsWith("jpg") || filename.endsWith("gif") 
                        || filename.endsWith("png")){
                    //前半部分路径,目录,将webRoot下一个名称为images文件夹转换成绝对路径
                    String leftPath = session.getServletContext().getRealPath("/image");
                    //进行路径拼接=前半部分路径+文件名称
                    File file = new File(leftPath,filename);
                    item.transferTo(file);
                }
            }
        }
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }
    return "success";
}

实现效果:
这里写图片描述

2.文件下载

前端download.jsp内容:
<h2>文件下载</h2>
<a href="download">download</a>

这里写图片描述

//文件下载Controller
@RequestMapping(value = "download",method=RequestMethod.GET)
public ResponseEntity<byte[]> download(HttpSession session){
    ResponseEntity<byte[]> response =null;
    try {
        byte[] body=null;
        ServletContext servletContext = session.getServletContext();
        InputStream in = servletContext.getResourceAsStream("/image/4.png");
        body = new byte[in.available()];
        in.read(body);
        HttpHeaders headers = new HttpHeaders();
        //响应头的名字和响应头的值
        headers.add("Content-Disposition", "attachment;filename=1.png");
        HttpStatus status = HttpStatus.OK;
        response = new ResponseEntity<byte[]>(body,headers,status);
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
    }
    return response;
}

实现效果:
这里写图片描述

这边使用SpringMvc实现的文件上传和下载比较简单,实际项目中考虑的问题比较多,有兴趣的可以深入研究,写的不好之处请指点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值