上传文件时,SpringMVC如何接收表单数据
1个回答
2018-07-31 · 国内最优秀java资源共享平台
关注
展开全部
用MultipartFile接收表单上传文件数据
案例:全过程
jsp
<form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
<h2>文件上传</h2>
文件:<input type="file" name="uploadFile"/><br/><br/>
<input type="submit" value="上传"/>
</form>
SpringMVC Controller
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam(value = "file", required = false) MultipartFile uploadFile, HttpServletRequest request, ModelMap model) {
System.out.println("开始");
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
String fileName = new Date().getTime()+".jpg";
System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
return "uploadResult";
}
案例:全过程
jsp
<form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
<h2>文件上传</h2>
文件:<input type="file" name="uploadFile"/><br/><br/>
<input type="submit" value="上传"/>
</form>
SpringMVC Controller
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam(value = "file", required = false) MultipartFile uploadFile, HttpServletRequest request, ModelMap model) {
System.out.println("开始");
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
String fileName = new Date().getTime()+".jpg";
System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
//保存
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);
return "uploadResult";
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询