Spring实战(第4版)第七章Spring MVC的高级技术学习笔记(multipart请求上传图片)

处理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()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值