Spring ------文件上传

第一步:导入包 

第二步:编写JSP

 

<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>

第三步配置 springmvc.xml  

异常解析器表示出现org.springframework.web.multipart.MaxUploadSizeE
xceededException 跳转到errop.jsp 而不是报错

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.Comm
onsMultipartResolver">
<property name="maxUploadSize"
value="50"></property>
</bean>
<!-- 异常解析器 -->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.Simple
MappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop
key="org.springframework.web.multipart.MaxUploadSizeE
xceededException">/error.jsp</prop>
</props>
</property>
</bean>

第四步 编写控制器类

MultipartFile 对象名必须和<input 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";
}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值