处理multipart数据请求
在webConfig.java中注册multipart解析器
@Bean
public MultipartResolver multipartResolver() throws IOException {
return new StandardServletMultipartResolver();//设置multipart解析器
}
自定义DispatacherServlet配置
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("/tmp/uploads", 1267501, 1367501, 0));
}
jsp页面改动点:
input标签:
HeadPicture : <input type="file" name="headPicture" id="headPicture" accept="image/jpeg,image/png,image/gif"/><br/>
FORM标签:
<sf:form method="POST" commandName="spitter" enctype="multipart/form-data" >
提交表单成功后,
D:\Users\T-shaoh\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Spitter6Jsp\tmp\uploads 路径下生成tmp文件(文件后缀为tmp),
D:\Users\T-shaoh\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Spitter6Jsp
为Tomcat service -> Modules 中的server path
接受MultipartFile
使用上传文件的原始byte比较简单但功能有限。spring提供了MultipartFile接口,它为处理multipart数据提供内容丰富的对象。
public interface MultipartFile {
String getName();
String getOriginalFilename();
String getContentType();
boolean isEmpty();
long getSize();
byte[] getBytes() throws IOException;
InputStream getInputStream() throws IOException;
void transferTo(File dest) throws IOException, IllegalStateException;
}
transferTo方法帮我们把上传的文件写入到文件系统,可以在Controller控制器方法内添加代码让上传图片写入文件系统。
1.processRegistration方法如下:
public String processRegistration(
// @RequestPart(value="headPicture", required=false) Part headPicture,
// @RequestPart("headPicture") byte[] headPicture,
@RequestPart(value="headPicture", required=false) MultipartFile headPicture,
@Valid Spitter spitter,
Errors errors) throws IllegalStateException, IOException {
if (errors.hasErrors()) {
return "registerForm";
}
spitterRepository.save(spitter);
//保存图片到文件系统中
headPicture.transferTo(new File("D:\\huanfile\\image\\" + spitter.getUsername() + ".jpg"));
return "redirect:/spitter/" + spitter.getUsername();
}
headPicture.transferTo
方法将文件转录到指定的路径下,filePath为D:\\huanfile\\image
目录下
还可以利用MultipartFile对象获取图片名字、原始名字、文件类型、文件大小等(image/png)headPicture.getContentType()