SpringMVC 文件上传

1. 基于 apache 的 commons-fileupload.jar 完成文件上传

2. MultipartResovler 作用:

    2.1 把客户端上传的文件流转换成 MutipartFile 封装类.

    2.2 通过 MutipartFile 封装类获取到文件流

3. 表单数据类型分类

    3.1 在<form>的 enctype 属性控制表单类型

    3.2 默认值 application/x-www-form-urlencoded,普通表单数据.(少量文字信息)

    3.3 text/plain 大文字量时使用的类型.邮件,论文

    3.4 multipart/form-data 表单中包含二进制文件内容.

4. 实现步骤:

    4.1 导入 springmvc 包和 apache 文件上传 commons-fileupload 和 commons-io 两个 jar

    4.2 编写 JSP 页面

<!-- 设置enctype属性 -->
<form action="upload" enctype="multipart/form-data" method="post">
    姓名:<input type="text" name="name"/><br/>
    文件:<input type="file" name="file"/><br/>
    <input type="submit" value="提交"/>
</form>

    4.3 配置 springmvc.xml

<!-- MultipartResovler 解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="50"></property>
</bean>
<!-- 异常解析器(发生异常跳转到那个页面) -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>
        </props>
    </property>
</bean>

    4.4 编写控制器类

        4.4.1 MultipartFile 对象名必须和的 <intput type="file"/>的name 属性值相同

@RequestMapping("upload")
public String upload(MultipartFile file,String name) throws IOException{
//获取文件名字(不同浏览器的值不同有的包含路径,有的不包含)
String fileName = file.getOriginalFilename();
//截取文件名的后缀
String suffix = fileName.substring(fileName.lastIndexOf("."));
//判断上传文件类型
if(suffix.equalsIgnoreCase(".png")){
//生成随机文件名
String uuid = UUID.randomUUID().toString();
//存储文件
FileUtils.copyInputStreamToFile(file.getInputStream(), new File("E:/"+uuid+suffix));
return "/index.jsp";
}else{
return "error.jsp";
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值