1. 程式人生 > >springMVC接收表單傳來的file,並上傳

springMVC接收表單傳來的file,並上傳

controller層

@RequestMapping(value = "/fileupload.do")

@ResponseBody
public JsonResult<Boolean> fileupload(@RequestParam(value = "imgUpload") MultipartFile uploadFile, HttpServletRequest request)  {
String contextPath = request.getSession().getServletContext().getRealPath("/document");
Boolean b = false;
try{
b = fileService.saveFile(uploadFile,contextPath);
}catch(Exception e){
return new JsonResult<Boolean>(e.getMessage());
}
return new JsonResult<Boolean>(b);

}

service層

@Transactional

public Boolean saveFile(MultipartFile uploadFile, String contextPath) {
String filename = uploadFile.getOriginalFilename();
String fpath = contextPath;
File file = new File(fpath+File.separator+filename);
try {
uploadFile.transferTo(file);//上傳檔案
} catch (IllegalStateException e) {
e.printStackTrace();
throw new IllegalStateException("儲存失敗");
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("儲存失敗");
}
fileDao.saveFile(filename,fpath);//儲存檔案路徑
return true;
}