java form 上传文件_JAVA入门[16]-form表单,上传文件

一、如何传递参数

@RequestMapping("/detail")

public String detail(@RequestParam("id") int id,Model model){

Category category=new Category();

category.setCateId(id);

category.setCateName("测试分类"+id);

model.addAttribute("cate",category);

return "detail.html";

}

@RequestMapping(value = "/edit/{id}",method = RequestMethod.GET)

public String edit(@PathVariable("id") int id,Model model) {

//todo:get category from db

Category category=new Category();

category.setCateId(id);

category.setCateName("测试分类"+id);

model.addAttribute("cate",category);

return "edit.html";

}

二、校验表单

1.首先定义实体类。

public class Category{

public Category(){}

@NotNull

@Min(1)

private int cateId;

@NotNull

private String cateName;

public int getCateId() {

return cateId;

}

public void setCateId(int cateId) {

this.cateId = cateId;

}

public String getCateName() {

return cateName;

}

public void setCateName(String cateName) {

this.cateName = cateName;

}

}

2.表单edit.html

id:
name:

3.通过给action方法的参数添加@Valid注解,这会告知Spring,需要确保这个对象满足校验限制

@RequestMapping(value = "/save",method = RequestMethod.POST)

public String save( @Valid Category category, Errors errors) throws IOException {...}

错误可以通过Errors对象进行访问,现在这个对象已作为processRegistration()方法的参数。(很重要一点需要注意,Errors参数要紧跟在带有@Valid注解的参数后面,@Valid注解所标注的就是要检验的参数。

三、上传图片

1.设置web.xml配置

web.xml配置multipart-config

springmvc

org.springframework.web.servlet.DispatcherServlet

1

2097152

4194304

2.from表单

form要将enctype属性设置为multipart/form-data,这就告诉浏览器以multipart数据的形式提交表单

input标签要把type设置为file,这能够让用户选择要上传的图片文件。accept属性用来将文件类型限制为JPEG、PNG以及GIF图片。根据其name属性,图片数据将会发送到multipart请求中的profilePicture part之中

id:
name:
file:

3.controller:

@RequestPart :图片对应的参数要添加该注解

spring提供了Multipart MultipartFile对象,它为处理multipart数据提供了内容更为丰富的对象

transferTo() ,它能够帮助我们将上传的文件写入到文件系统中

@RequestMapping(value = "/save",method = RequestMethod.POST)

public String save(@RequestPart("picture") MultipartFile picture, @Valid Category category, Errors errors) throws IOException {

//todo:save file to image server

String filepath=request.getRealPath("/")+"upload/"+picture.getOriginalFilename();

picture.transferTo(new File(filepath));

if(errors.hasErrors()){

return "edit.html";

}

//todo:save category to db

return "redirect:/category/detail?id="+category.getCateId();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值