Java組件commons fileupload實(shí)現(xiàn)文件上傳功能
Apache提供的commons-fileupload jar包實(shí)現(xiàn)文件上傳確實(shí)很簡單,最近要用Servlet/JSP做一個圖片上傳功能,在網(wǎng)上找了很多資料,大多是基于struts框架介紹的,還有些雖然也介紹common-fileupload的上傳,但是那些例子比較老,有些類現(xiàn)在都廢棄了。
通過研究學(xué)習(xí)總結(jié),終于完成了這個上傳功能,下面與大家分享一下。
案例場景
一個圖書館后臺管理界面,需要提供上傳圖書圖片的功能并且最終顯示在頁面中。
實(shí)現(xiàn)效果
進(jìn)入添加書籍頁面,默認(rèn)顯示一個圖片“暫無突破”(長寬均為200px),提供一個按鈕“上傳圖片”,如下圖效果。
點(diǎn)擊“上傳圖片”按鈕,通過模式窗口彈出上傳界面,如下圖所示。
通過“瀏覽”按鈕選擇指定圖片,點(diǎn)擊“上傳”按鈕進(jìn)行上傳,如果上傳成功則彈出成功提示,用戶點(diǎn)擊“確定”后關(guān)閉彈出窗并自動將新圖片顯示在頁面上,如下圖所示。
代碼實(shí)現(xiàn)
①首先創(chuàng)建一個添加書籍頁面:bookAdd.jsp
頁面id為photo_id的hidden標(biāo)簽用于存儲圖片路徑,方便提交到后臺存放到數(shù)據(jù)庫,id為img_id的<img>標(biāo)簽用于顯示圖片,所有圖片都存放在服務(wù)器下,方便讀取。然后一個關(guān)鍵js,點(diǎn)擊button通過模式窗口彈出上傳頁面,在彈出模式窗口時定義了一個變量win,該變量用于獲取模式窗口傳回的圖片路徑值。
(注意:因?yàn)榘踩詥栴}圖片不能圖片不能隨意存放,項目部署在服務(wù)器中,圖片就只能放在該服務(wù)器下才能查看得到,如果一定要讀取非當(dāng)前服務(wù)器下的圖片需要配置服務(wù)器的虛擬目錄)
<html> <head> <title>添加書籍</title> <script type="text/javascript"> //打開上傳頁面 function openUpload(){ var win = window.showModalDialog("<%=root%>/Admin/bookUpload.jsp","","dialogWidth:300px;dialogHeight:300px;scroll:no;status:no"); if(win != null){ document.getElementById("photo_id").value = win; document.getElementById("img_id").src = "<%=root%>/"+win; } } </script> </head> <body> <h5>添加書籍</h5><hr/> <p> 書的封面: <label> <input type="hidden" id="photo_id" name="photo" value="images/noimg.png"><input type="button" onclick="openUpload()" value="上傳圖片"/><br/> <img id="img_id" alt="" src="<%=root%>/images/noimg.png" width="200px" height="200px"> </label> </p> </body> </html>
②創(chuàng)建上傳圖片頁面,bookUpload.jsp
注意一定要定義<base>標(biāo)簽,當(dāng)前模式窗口關(guān)閉時才能將數(shù)據(jù)返回到父窗體,<form>標(biāo)簽還要設(shè)置一個屬性enctype="multipart/form-data"這樣提交的文件才能被后臺獲取,點(diǎn)擊“上傳”button即可將文件向后臺傳送,剩下的重頭戲就是后臺上傳處理了。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <meta http-equiv="pragma" content="no-cache" /> <span style="color: #ff0000;"><base target="_self"></span> <title>書籍圖片上傳</title> </head> <body> <h5>圖片上傳</h5><hr/> <p style="color: red">${requestScope.errorMsg}</p> <form id="form1" name="form1" action="<%=root%>/BookServlet?type=bookUpload" method="post" enctype="multipart/form-data"> <div>注:圖片大小最大不能超過3M!</div> <div><input type="file" name="file_upload"/></div> <div><input type="submit" value="上傳"/></div> </form> </body> </html>
③創(chuàng)建一個普通的Servlet,下面只提供部分關(guān)鍵代碼
紅色代碼部分是上傳的關(guān)鍵代碼,其它就是作為點(diǎn)綴了。完成這三步,一個簡單的上傳即實(shí)現(xiàn)了。
public class BookServlet extends HttpServlet { private String uploadPath = "eShop/upload/"; // 上傳文件的目錄 private String tempPath = "eShop/uploadtmp/"; // 臨時文件目錄 private String serverPath = null; private int sizeMax = 3;//圖片最大上限 private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"}; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { serverPath = getServletContext().getRealPath("/").replace("\\", "/"); //Servlet初始化時執(zhí)行,如果上傳文件目錄不存在則自動創(chuàng)建 if(!new File(serverPath+uploadPath).isDirectory()){ new File(serverPath+uploadPath).mkdirs(); } if(!new File(serverPath+tempPath).isDirectory()){ new File(serverPath+tempPath).mkdirs(); } <span style="color: #ff0000;">DiskFileItemFactory factory = new DiskFileItemFactory();</span> factory.setSizeThreshold(5*1024); //最大緩存 factory.setRepository(new File(serverPath+tempPath));//臨時文件目錄 <span style="color: #ff0000;">ServletFileUpload upload = new ServletFileUpload(factory);</span> upload.setSizeMax(sizeMax*1024*1024);//文件最大上限 String filePath = null; try { <span style="color: #ff0000;">List<FileItem> items = upload.parseRequest(request);</span>//獲取所有文件列表 for (FileItem item : items) { //獲得文件名,這個文件名包括路徑 <span style="color: #ff0000;">if(!item.isFormField()){</span> //文件名 String fileName = item.getName().toLowerCase(); if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){ String uuid = UUID.randomUUID().toString(); filePath = serverPath+uploadPath+uuid+fileName.substring(fileName.lastIndexOf(".")); <span style="color: #ff0000;">item.write(new File(filePath));</span> PrintWriter pw = response.getWriter(); pw.write("<script>alert('上傳成功');window.returnValue='"+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."))+"';window.close();</script>"); pw.flush(); pw.close(); }else{ request.setAttribute("errorMsg", "上傳失敗,請確認(rèn)上傳的文件存在并且類型是圖片!"); request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request, response); } } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("errorMsg", "上傳失敗,請確認(rèn)上傳的文件大小不能超過"+sizeMax+"M"); request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request, response); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java組件SmartUpload和FileUpload實(shí)現(xiàn)文件上傳功能
- Java中使用fileupload組件實(shí)現(xiàn)文件上傳功能的實(shí)例代碼
- java使用common-fileupload實(shí)現(xiàn)文件上傳
- java組件commons-fileupload實(shí)現(xiàn)文件上傳、下載、在線打開
- JavaEE組件commons-fileupload實(shí)現(xiàn)文件上傳、下載
- java組件commons-fileupload文件上傳示例
- java組件fileupload文件上傳demo
- java組件commons-fileupload實(shí)現(xiàn)文件上傳
- JAVA使用commos-fileupload實(shí)現(xiàn)文件上傳與下載實(shí)例解析
- 使用fileupload組件實(shí)現(xiàn)文件上傳功能
相關(guān)文章
Java并發(fā)編程如何降低鎖粒度并實(shí)現(xiàn)性能優(yōu)化
這篇文章主要介紹了Java并發(fā)編程如何降低鎖粒度并實(shí)現(xiàn)性能優(yōu)化,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08java實(shí)現(xiàn)堆排序以及時間復(fù)雜度的分析
本文主要介紹了java實(shí)現(xiàn)堆排序以及時間復(fù)雜度,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12idea中安裝VisualVM監(jiān)控jvm的圖文教程
這篇文章主要介紹了idea中安裝VisualVM監(jiān)控jvm的教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09設(shè)計模式之模版方法模式_動力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了設(shè)計模式之模版方法模式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08