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();
}
總結
以上是生活随笔為你收集整理的java form 上传文件_JAVA入门[16]-form表单,上传文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python不定长参数怎么相加_pyth
- 下一篇: aidl生成java文件_Android