SpringMVC-文件上传和下载

文件上传和下载

介绍

文件上传和下载是项目开发中的最常见的功能之一,文件上传是从浏览器中将文件以流的形式提交给服务器,文件下载是从浏览器请求服务器,服务器将web应用管理系统的文件资源提供给用户下载。

SpringMVC默认情况下不能处理文件上传工作,如需则要配置MultipartResolver。

前端表单enctype详细说明

  • application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。

  • multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。

  • text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。

注意

上传文件需要配置CommonsMultipartResolver,而一个MultipartResolver实现类是使用Apache Commons FileUpload技术实现的。所以pringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。

文件上传:

1.导入文件上传的jar包

 <dependencies>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.1.9.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.9.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

2.配置applicationContext.xml文件的multipartResolver

 <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

3.编写前端页面

<%--  multipart/form-data 以二进制形式传输--%>
  <form method="post" action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="提交"/>
  </form>

4.Controller类

1.常规方法

@Controller
public class UploadFileDemo {
//    @RequestParam(file)将name=file控件得到的文件封装成CommonsMultipartFile对象
//批量上传CommonsMultipartFile为数组即可
    @RequestMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest req) throws IOException {
        //1.得到上传文件名
        String ofName = file.getOriginalFilename();
       if("".equals(ofName)){
           //无上传重定向到index页面
           return "null";
       }
        System.out.println(ofName);
       //getServletContext()获取Servlet上下文对象
        //2.req.getServletContext().getRealPath("/f") 给定一个URI,返回文件系统中URI对应的绝对路径,如果不能映射,则返回null
        String path = req.getServletContext().getRealPath("/upload");
        //如果路径不存在,则创建一个
        File realPath = new File(path);
        if(!realPath.exists())
        {
            realPath.mkdir();
        }
        System.out.println("上传文件保存位置"+realPath);
        //获得文件输入流
        InputStream is = file.getInputStream();
        //获取文件输出流
        FileOutputStream fis = new FileOutputStream(new File(realPath,ofName));
        byte[] buffer = new byte[1024];
        int len=0;
        while((len=is.read(buffer))>0)
        {
            fis.write(buffer,0,len);
            //刷新
            fis.flush();
        }
        fis.close();
        is.close();
        return null;
    }

5.启动Tomcat测试
在这里插入图片描述

使用file.Transto 来保存上传的文件

controller层编写

   @RequestMapping("/upload2")
    @ResponseBody
    public String updateFile02(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req) throws IOException {
        String ofName = file.getOriginalFilename();
        System.out.println(ofName);
        if("".equals(ofName)){
            return "null";
        }
        String realPath = req.getServletContext().getRealPath("/upload");

        //使用CommonsMultipartFile的transferTO直接上传文件
        file.transferTo(new File(realPath+"/"+ofName));
        return "null";
    }

文件下载


    @RequestMapping("/down")
    @ResponseBody
    public String downFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String path = req.getServletContext().getRealPath("/upload");
        //下载文件名
        String fileName ="例4.17.txt";

        //设置文本响应头
        resp.reset(); //设置页面不缓存,清空buffer
        resp.setCharacterEncoding("UTF-8"); //字符编码
        resp.setContentType("multipart/form-data"); //二进制传输数据
        resp.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));

        File file =new File(path,fileName);
        //读取文件-- 输入流
        InputStream is = new FileInputStream(file);
        //写出文件--输出流
        OutputStream os = resp.getOutputStream();
        int len =0;
        byte[] bf = new byte[1024];
        while((len=is.read(bf))>0){
            os.write(bf,0,len);
            os.flush();
        }
        os.close();
        is.close();
        System.out.println("文件下载成功");
        return null;
    }

前端页面:

<a href="/download">点击下载</a>

测试结果

在这里插入图片描述

相比于Java web 的Servlet,来说非常的简洁,上传的时候只需要管理一个CommonsMultipartResolver的bean。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值