报错更改 Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] wit
严重: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException
使用input上传文件时候出错,因为在form里提交了图文件,需要进行二进制编码,而我却少了这部分,即enctype="multipart/form-data"。更改后无错。
表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。
默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;
只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作。
enctype="multipart/form-data"是上传二进制数据,form里面的input的值以2进制的方式传过去。
核心代码如下:
jsp:
<form action="ManagerUpdate" onsubmit="return checkPwd()" enctype="multipart/form-data" method="post" > <div> <input type="hidden" value="${manager.id}" name="id"> </div> <div class="sign-u" style="margin-bottom: 20px"> <span> <img src="<%=path %>/upload/${manager.pic}" onerror="this.src='<%=path %>/upload/manager.png'" style="width: 20%;height: 20%;margin-left: 15%;border: 2px solid black"> </span> <label><input type="file" name="file" id="file" style="display: none" autocomplete="off" /><strong style="color: #01AAED;"> 上传头像</strong></label> <div class="clearfix"> </div> </div> </form>
Controller:
@RequestMapping(value = "ManagerUpdate") public String ManagerUpdate(Manager manager,MultipartFile file,HttpServletRequest request) throws IOException { //处理流业务 String path = request.getServletContext().getRealPath("/upload");//虚拟路径 File dir = new File(path);//把虚拟路径存储到流中, dir.mkdirs();//查询是否存在此文件夹,如果存在无操作,如果不存在这里自动创建; String srcName = file.getOriginalFilename();//获取流中的文件名称 File dest = new File(dir, srcName);//spring自动封装的流上传函数 file.transferTo(dest);//文件上传 manager.setPic(srcName); boolean b = managerservice.updateManager(manager); request.setAttribute("b",b); return "redirect:ManagerShow"; }
学习链接:https://www.iteye.com/blog/zkliqiang-779285