首先導入文件上傳的jar包
然后在Spring-servlet.xml文件中設置上傳文件解析器
1 <!--上傳文件解析器--> 2 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <!-- 設定默認編碼 --> 4 <property name="defaultEncoding" value="UTF-8"></property> 5 <!-- 設定文件上傳的最大值5MB,5*1024*1024 --> 6 <property name="maxUploadSize" value="5242880"></property> 7 </bean> 8 9 <mvc:resources location="/static/upload/" mapping="/upload/**"/>
前端頁面一定要用post請求
在控制類中寫實現功能,如果是一圖片的命名可以用:用戶名_png,不用再新建一個字段來存儲。
1 //插入(增加)--Post方法 2 @RequestMapping(value = "/insert", method = RequestMethod.POST) 3 public String insert(HttpServletResponse resp,HttpServletRequest req, Lwl lwl, MultipartFile fname) throws IOException { 4 resp.setContentType("text/html;charset=UTF-8"); 5 log.debug("上傳的文件:"+fname.getOriginalFilename()); 6 String sPath = req.getServletContext().getRealPath("/")+"/static/upload/"; 7 log.debug(sPath); 8 9 fname.transferTo(new File(sPath+lwl.getLwla()+"_.png") );//保存文件 10 11 lwl.setLwld(lwl.getLwla()+"_.png");//定義名字 12 if (lwlService.insertLwl(lwl)) { 13 return "redirect:/lwl"; 14 } else { 15 req.setAttribute("error", "addLwl falilure"); 16 return "addLwl"; 17 } 18 }
在web下新建一個文件夾
注意的是還要查看下面這個路徑下有沒有這個新建的文件夾,如果這里沒有,就在這里新建一個即可。
在前端顯示頁面加載即可
然后就可以加載出來了