SpringMVC 文件上传 详解

SpringMVC 为文件上传提供直接支持,通过 MultipartResolver 实现

配置 MultipartResolver,在 spring-mvc.xml 文件中
<!-- 文件上传 -->
< bean id ="multipartResolver"
         class ="org.springframework.web.multipart.commons.CommonsMultipartResolver"
         p :defaultEncoding ="UTF-8"
         p :maxUploadSize =" 104857600 "
          p :maxInMemorySize ="4096"
         p :uploadTempDir ="upload/temp" />   

在 Controller 中
RequestMapping(value = "/uploadPage" )
public String updatePage() {
    return "uploadPage" ;
}

@RequestMapping(value = "/upload" )
public String updateThumb(@RequestParam( "name" ) String name, @RequestParam( "file" ) MultipartFile file) throws Exception {
    if (!file.isEmpty()) {
        file.transferTo( new File( "d:/temp/" + file.getOriginalFilename()));// 将上传文件保存到一个目标文件中
        return "redirect:success.html" ;
    }
    else {
        return "redirect:fail.html" ;
    }
}

在 uploadPage.jsp 中
<%@ page language =" java " contentType =" text/html; charset=UTF-8 " pageEncoding =" UTF-8 "%>
<%@ taglib prefix =" c uri =" http://java.sun.com/jsp/jstl/core " %>
< html >
   < head >
      < title > 请上传用户头像 </ title >
   </ head >
   < body >
      < h1 > 请选择上传的头像文件 </ h1 >
      < form method= "post" action= " < c :url value ="/user/upload.html" /> " enctype= "multipart/form-data" >
         < input type= "text" name= "name" />
         < input type= "file" name= "file" />
         < input type= "submit" />
      </ form >
   </ body >
</ html >

MultipartFile 常用方法


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值