Spring MVC 处理multipart (JavaConfig )

例子为上传一张图片
配置multipart

使用standardServletMultipartResolver依赖于Servlet 3.0对multipart请求的支持(始于Spring 3.1)
Servlet包要配置成3.0或以上的

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>

配置MultipartResolver

@Configuration
public class MultipartResolverConfig {
    @Bean
    public MultipartResolver multipartResolver() throws IOException{
        return new StandardServletMultipartResolver();
    }
}
@Import({ MultipartResolverConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter{
....
}

配置上传属性

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
.....
@Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        //限制文件的大小不超过2MB,整个请求不超过4MB,而且所有的文件都要写到磁盘中
        String location = "d://tmp//spittr//uploads//";
        registration.setMultipartConfig(new MultipartConfigElement(location,20971520, 41943040, 0));

    }
.....
}

处理multipart请求

@RequestMapping(value = "/register",method=RequestMethod.POST)
    public String processRegister(
            @RequestPart("profilePicture") MultipartFile profilePicture) throws IOException{
        String location = "d://tmp//spittr//uploads//";
        profilePicture.transferTo(new File(location + profilePicture.getOriginalFilename()));
        return "ok";
    }

发起multipart请求

<form method="POST" enctype="multipart/form-data">
      Picture:<input type="file" name="profilePicture" accept="image/jpeg,image/png,image/gif" /><br/>
      <input type="submit" value="Register" />
    </form>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值