SpringMVC上传文件

SpringMVC文件上传

1. 编写hello工程

1.1 导入依赖

导入apache提供的jar包

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

1.2 配置spirngMVC配置文件

<!-- 文件上传配置 -->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
        <property name="defaultEncoding" value="utf-8"></property>
        <!-- 最大上传限制100MB -->
        <property name="maxUploadSize" value="104857600"></property>
        <property name="maxInMemorySize" value="40960"></property>
    </bean>

1.3 编写测试jsp页面

form表单一定要加上 enctype=“multipart/form-data” 属性,还要为file添加name属性,否则会报错!
提交方式建议post,使用get提交会限制文件大小。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <p><input type="file" name="file1"></p>
    <p><input type="submit" name="提交"></p>
</form>
</body>
</html>

1.4 编写测试接口

/**
     * 将提交上来的文件封装为CommonsMultipartFile对象
     * 批量上传:将CommonsMultipartFile设置为数组即可
     */
    @PostMapping("/upload")
    public void upload(@RequestParam("file1")CommonsMultipartFile file){
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //获取文件名字
            String filename = file.getOriginalFilename();
            inputStream = file.getInputStream();
            fileOutputStream = new FileOutputStream("/Users/sheepl/Downloads/"+UUID.randomUUID()+filename);
            //文件读取
            int readLength;
            byte[] data = new byte[1024*1024];
            while ((readLength = inputStream.read(data)) != -1){
                fileOutputStream.write(data,0,readLength);
            }
            //刷新文件输出流
            fileOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //关闭流前先判断是否为空,防止空指针
        try {
            if (inputStream != null){
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if(fileOutputStream != null){
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1.5 启动tomcat查看运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值