JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能
本文實(shí)例為大家分享了JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能的具體代碼,供大家參考,具體內(nèi)容如下
項(xiàng)目目錄結(jié)構(gòu)大致如下:
正如我在上圖紅線(xiàn)畫(huà)的三個(gè)東西:Dao、service、servlet 這三層是主要的結(jié)構(gòu),類(lèi)似 MVC 架構(gòu),Dao是模型實(shí)體類(lèi)(邏輯層),service是服務(wù)層,servlet是視圖層,三者協(xié)作共同完成項(xiàng)目。
這里的User是由user表來(lái)定義的一個(gè)類(lèi),再封裝增刪改查等操作,實(shí)現(xiàn)從數(shù)據(jù)庫(kù)查詢(xún)與插入,修改與刪除等操作,并實(shí)現(xiàn)了分頁(yè)操作,也實(shí)現(xiàn)了將圖片放到服務(wù)器上運(yùn)行的效果。
Dao層:主要實(shí)現(xiàn)了User類(lèi)的定義,接口IUserDao的定義與實(shí)現(xiàn)(UserDaoImpl);
service層:直接定義一個(gè)接口類(lèi)IUserService,與IUserDao相似,再實(shí)現(xiàn)其接口類(lèi)UserServiceImpl,直接實(shí)例化UserDaoImpl再調(diào)用其方法來(lái)實(shí)現(xiàn)自己的方法,重用了代碼。詳見(jiàn)代碼吧;
servlet層:起初是將表User 的每個(gè)操作方法都定義成一個(gè)servlet 去實(shí)現(xiàn),雖然簡(jiǎn)單,但是太多了,不好管理,于是利用 基類(lèi)BaseServlet 實(shí)現(xiàn)了“反射機(jī)制”,通過(guò)獲取的 action 參數(shù)自己智能地調(diào)用對(duì)應(yīng)的方法,而UserServlet則具體實(shí)現(xiàn)自己的方法,以供調(diào)用,方便許多,詳見(jiàn)之前的博文或下述代碼。
將文件上傳到 tomcat 服務(wù)器的編譯后運(yùn)行的過(guò)程的某個(gè)文件關(guān)鍵要在每次編譯后手動(dòng)為其創(chuàng)建該文件夾來(lái)存放相應(yīng)的上傳文件,否則會(huì)導(dǎo)致每次重啟 tomcat 服務(wù)器后該編譯后的工程覆蓋了原先的,導(dǎo)致上傳文件存放的文件夾不存在,導(dǎo)致代碼找不到該文件夾而報(bào)錯(cuò),即上傳不成功。如下圖所示:
主要是考慮圖片路徑的問(wèn)題,手工設(shè)置路徑肯定不能保證不重復(fù),所以取到上傳圖片的后綴名后利用隨機(jī)生成的隨機(jī)數(shù)作為圖片名,這樣就不會(huì)重復(fù)名字了:
String extendedName = picturePath.substring(picturePath.lastIndexOf("."),// 截取從最后一個(gè)'.'到字符串結(jié)束的子串。 picturePath.length()); // 把文件名稱(chēng)重命名為全球唯一的文件名 String uniqueName = UUID.randomUUID().toString(); saveFileName = uniqueName + extendedName;// 拼接路徑名
增加用戶(hù)時(shí)代碼如下:
// 增 public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("add方法被調(diào)用"); // 獲取數(shù)據(jù) int id = 0; String username = null; String password = null; String sex = null; Date birthday = null; String address = null; String saveFileName = null; String picturePath = null; // 得到表單是否以enctype="multipart/form-data"方式提交 boolean isMulti = ServletFileUpload.isMultipartContent(request); if (isMulti) { // 通過(guò)FileItemFactory得到文件上傳的對(duì)象 FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fif); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { // 判斷是否是普通表單控件,或者是文件上傳表單控件 boolean isForm = item.isFormField(); if (isForm) {// 是普通表單控件 String name = item.getFieldName(); if ("id".equals(name)) { id = Integer.parseInt(item.getString("utf-8")); System.out.println(id); } if ("sex".equals(name)) { sex = item.getString("utf-8"); System.out.println(sex); } if ("username".equals(name)) { username = item.getString("utf-8"); System.out.println(username); } if ("password".equals(name)) { password = item.getString("utf-8"); System.out.println(password); } if ("birthday".equals(name)) { String birthdayStr = item.getString("utf-8"); SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd"); try { birthday = sdf.parse(birthdayStr); } catch (ParseException e) { e.printStackTrace(); } System.out.println(birthday); } if ("address".equals(name)) { address = item.getString("utf-8"); System.out.println(address); } if ("picturePath".equals(name)) { picturePath = item.getString("utf-8"); System.out.println(picturePath); } } else {// 是文件上傳表單控件 // 得到文件名 xxx.jpg String sourceFileName = item.getName(); // 得到文件名的擴(kuò)展名:.jpg String extendedName = sourceFileName.substring( sourceFileName.lastIndexOf("."), sourceFileName.length()); // 把文件名稱(chēng)重命名為全球唯一的文件名 String uniqueName = UUID.randomUUID().toString(); saveFileName = uniqueName + extendedName; // 得到上傳到服務(wù)器上的文件路徑 // C:\\apache-tomcat-7.0.47\\webapps\\taobaoServlet4\\upload\\xx.jpg String uploadFilePath = request.getSession() .getServletContext().getRealPath("upload/"); File saveFile = new File(uploadFilePath, saveFileName); // 把保存的文件寫(xiě)出到服務(wù)器硬盤(pán)上 try { item.write(saveFile); } catch (Exception e) { e.printStackTrace(); } } } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 2、封裝數(shù)據(jù) User user = new User(id, username, password, sex, birthday, address, saveFileName); // 3、調(diào)用邏輯層API IUserService iUserService = new UserServiceImpl(); // 4、控制跳轉(zhuǎn) HttpSession session = request.getSession(); if (iUserService.save(user) > 0) { System.out.println("添加新用戶(hù)成功!"); List<User> users = new ArrayList<User>(); users = iUserService.listAll(); session.setAttribute("users", users); response.sendRedirect("UserServlet?action=getPage"); } else { System.out.println("添加新用戶(hù)失??!"); PrintWriter out = response.getWriter(); out.print("<script type='text/javascript'>"); out.print("alert('添加新用戶(hù)失敗!請(qǐng)重試!');"); out.print("</script>"); } }
修改用戶(hù)時(shí)注意考慮圖片更改和沒(méi)更改這兩種情況,圖片更改時(shí)要先獲取原圖片并刪除其在服務(wù)器上的圖片,再添加新圖片到服務(wù)器;圖片不更改時(shí)則無(wú)需更新圖片路徑。
// 改 public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("update方法被調(diào)用"); HttpSession session = request.getSession(); // 獲取數(shù)據(jù) int id = (int)session.getAttribute("id"); String username = null; String password = null; String sex = null; Date birthday = null; String address = null; String saveFileName = null; String picturePath = null; IUserService iUserService = new UserServiceImpl(); // 得到表單是否以enctype="multipart/form-data"方式提交 boolean isMulti = ServletFileUpload.isMultipartContent(request); if (isMulti) { // 通過(guò)FileItemFactory得到文件上傳的對(duì)象 FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fif); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { // 判斷是否是普通表單控件,或者是文件上傳表單控件 boolean isForm = item.isFormField(); if (isForm) {// 是普通表單控件 String name = item.getFieldName(); if ("sex".equals(name)) { sex = item.getString("utf-8"); System.out.println(sex); } if ("username".equals(name)) { username = item.getString("utf-8"); System.out.println(username); } if ("password".equals(name)) { password = item.getString("utf-8"); System.out.println(password); } if ("birthday".equals(name)) { String birthdayStr = item.getString("utf-8"); SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd"); try { birthday = sdf.parse(birthdayStr); } catch (ParseException e) { e.printStackTrace(); } System.out.println(birthday); } if ("address".equals(name)) { address = item.getString("utf-8"); System.out.println(address); } if ("picturePath".equals(name)) { picturePath = item.getString("utf-8"); System.out.println(picturePath); } } else {// 是文件上傳表單控件 // 得到文件名 xxx.jpg picturePath = item.getName(); if (picturePath != "") {// 有選擇要上傳的圖片 // 得到文件名的擴(kuò)展名:.jpg String extendedName = picturePath.substring( picturePath.lastIndexOf("."),// 截取從最后一個(gè)'.'到字符串結(jié)束的子串。 picturePath.length()); // 把文件名稱(chēng)重命名為全球唯一的文件名 String uniqueName = UUID.randomUUID().toString(); saveFileName = uniqueName + extendedName;// 拼接路徑名 // 得到上傳到服務(wù)器上的文件路徑 // C:\\apache-tomcat-7.0.47\\webapps\\CommonhelloWorldServlet\\upload\\xx.jpg String uploadFilePath = request.getSession() .getServletContext().getRealPath("upload/"); File saveFile = new File(uploadFilePath, saveFileName); // 把保存的文件寫(xiě)出到服務(wù)器硬盤(pán)上 try { item.write(saveFile); } catch (Exception e) { e.printStackTrace(); } // 3、調(diào)用邏輯層 API // 根據(jù)id查詢(xún)用戶(hù)并獲取其之前的圖片 User user = iUserService.getUserById(id); String oldPic = user.getPicturePath(); String oldPicPath = uploadFilePath + "\\" + oldPic; File oldPicTodelete = new File(oldPicPath); oldPicTodelete.delete();// 刪除舊圖片 } } } } catch (NumberFormatException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } } System.out.println(id + "\t" + username + "\t" + password + "\t" + sex + "\t" + address + "\t" + picturePath + "\t" + birthday); // 2、封裝數(shù)據(jù) User user = new User(id, username, password, sex, birthday, address, saveFileName); if (iUserService.update(user) > 0) { System.out.println("修改數(shù)據(jù)成功!"); List<User> users = new ArrayList<User>(); users = iUserService.listAll(); session.setAttribute("users", users); // 4、控制跳轉(zhuǎn) response.sendRedirect("UserServlet?action=getPage"); } else { System.out.println("修改數(shù)據(jù)失?。?); PrintWriter out = response.getWriter(); out.print("<script type='text/javascript'>"); out.print("alert('修改數(shù)據(jù)失?。≌?qǐng)重試!');"); out.print("</script>"); } }
刪除的話(huà)就比較簡(jiǎn)單了,直接獲取原圖片路徑并刪除,則原圖片在服務(wù)器上被刪除。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- js實(shí)現(xiàn)圖片上傳到服務(wù)器和回顯
- Node.js HTTP服務(wù)器中的文件、圖片上傳的方法
- NodeJs實(shí)現(xiàn)簡(jiǎn)易WEB上傳下載服務(wù)器
- 詳解Node.js一行命令上傳本地文件到服務(wù)器
- js實(shí)現(xiàn)圖片粘貼上傳到服務(wù)器并展示的實(shí)例
- 基于HTML5+js+Java實(shí)現(xiàn)單文件文件上傳到服務(wù)器功能
- 利用nodejs監(jiān)控文件變化并使用sftp上傳到服務(wù)器
- NodeJS與HTML5相結(jié)合實(shí)現(xiàn)拖拽多個(gè)文件上傳到服務(wù)器的實(shí)現(xiàn)方法
- Ajax上傳實(shí)現(xiàn)根據(jù)服務(wù)器端返回?cái)?shù)據(jù)進(jìn)行js處理的方法
- js實(shí)現(xiàn)上傳圖片到服務(wù)器
相關(guān)文章
jsp和servlet操作mysql中文亂碼問(wèn)題的解決辦法
自己做測(cè)試的時(shí)候用到j(luò)sp/servlet 向mysql中寫(xiě)數(shù)據(jù),但是中文總是亂碼,今早糾結(jié)了半天才搞定,分享給大家我的解決辦法2014-04-04JSP+EXt2.0實(shí)現(xiàn)分頁(yè)的方法
這篇文章主要介紹了JSP+EXt2.0實(shí)現(xiàn)分頁(yè)的方法,涉及JavaScript結(jié)合JSP遍歷及分頁(yè)的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09jsp之間傳參數(shù)接受中文有亂碼問(wèn)題解決方法
這篇文章主要介紹了jsp之間傳參數(shù)接受中文有亂碼問(wèn)題解決方法,需要的朋友可以參考下2014-06-06用JSP下載word文件(不會(huì)直接用IE打開(kāi))
用JSP下載word文件(不會(huì)直接用IE打開(kāi))...2006-10-10JSP對(duì)JavaBean的各種常用操作方法總結(jié)
這篇文章主要介紹了JSP對(duì)JavaBean的各種常用操作方法總結(jié),包括對(duì)JavaBean屬性的設(shè)置獲取移除等,是JSP入門(mén)的基礎(chǔ),需要的朋友可以參考下2016-04-04使用jsp調(diào)用javabean實(shí)現(xiàn)超簡(jiǎn)單網(wǎng)頁(yè)計(jì)算器示例
這篇文章主要介紹了使用jsp和javabean實(shí)現(xiàn)超簡(jiǎn)單網(wǎng)頁(yè)計(jì)算器示例,需要的朋友可以參考下2014-04-04