今天实现一个上传照片的功能,之前没接触过mvc,在网上搜索过后实现了文件上传,下面是我写的demo.
jsp页面以表单形式提交需要上传的文件:
<form id="article"action="<%=basePath%>app/uploadPic" method="post" enctype="multipart/form-data">
<div>
<font style="font-size: 24px;">上传文件:</font><input type="file" name="file"/>
</div>
</form>
注意:表单需要加上enctype="multipart/form-data",在controller里以MultipartFile接收的请求的数据。
controller代码
@Controller
public class WebUserController extends BaseController {
@RequestMapping(value="/uploadPic",method = {RequestMethod.POST,RequestMethod.GET})
public String saveHuaTi(@RequestParam(value = "file", required = false) MultipartFile file,ModelMap map,HttpSession session,HttpServletRequest request,HttpServletResponse response){
String result = "";//返回结果
try {
File targetFile = null;
if(file != null){
String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
//保存到服务端上
file.transferTo(targetFile);
}
}
} catch (Exception e) {
log.error("上传图片失败:{}", e);
}
return "uploadsuccess";
}
}