1. 程式人生 > 實用技巧 >JavaWeb實現圖片上傳功能

JavaWeb實現圖片上傳功能

首先匯入檔案上傳的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下新建一個資料夾

注意的是還要檢視下面這個路徑下有沒有這個新建的資料夾,如果這裡沒有,就在這裡新建一個即可。

在前端顯示頁面載入即可

然後就可以加載出來了