国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java組件commons fileupload實現文件上傳功能

2019-11-26 13:42:46
字體:
來源:轉載
供稿:網友

Apache提供的commons-fileupload jar包實現文件上傳確實很簡單,最近要用Servlet/JSP做一個圖片上傳功能,在網上找了很多資料,大多是基于struts框架介紹的,還有些雖然也介紹common-fileupload的上傳,但是那些例子比較老,有些類現在都廢棄了。

通過研究學習總結,終于完成了這個上傳功能,下面與大家分享一下。

案例場景

一個圖書館后臺管理界面,需要提供上傳圖書圖片的功能并且最終顯示在頁面中。

實現效果

進入添加書籍頁面,默認顯示一個圖片“暫無突破”(長寬均為200px),提供一個按鈕“上傳圖片”,如下圖效果。

 

點擊“上傳圖片”按鈕,通過模式窗口彈出上傳界面,如下圖所示。

通過“瀏覽”按鈕選擇指定圖片,點擊“上傳”按鈕進行上傳,如果上傳成功則彈出成功提示,用戶點擊“確定”后關閉彈出窗并自動將新圖片顯示在頁面上,如下圖所示。

代碼實現

 ①首先創建一個添加書籍頁面:bookAdd.jsp

 頁面id為photo_id的hidden標簽用于存儲圖片路徑,方便提交到后臺存放到數據庫,id為img_id的<img>標簽用于顯示圖片,所有圖片都存放在服務器下,方便讀取。然后一個關鍵js,點擊button通過模式窗口彈出上傳頁面,在彈出模式窗口時定義了一個變量win,該變量用于獲取模式窗口傳回的圖片路徑值。

 (注意:因為安全性問題圖片不能圖片不能隨意存放,項目部署在服務器中,圖片就只能放在該服務器下才能查看得到,如果一定要讀取非當前服務器下的圖片需要配置服務器的虛擬目錄)

<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> 

  ②創建上傳圖片頁面,bookUpload.jsp

 注意一定要定義<base>標簽,當前模式窗口關閉時才能將數據返回到父窗體,<form>標簽還要設置一個屬性enctype="multipart/form-data"這樣提交的文件才能被后臺獲取,點擊“上傳”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> 

  ③創建一個普通的Servlet,下面只提供部分關鍵代碼

 紅色代碼部分是上傳的關鍵代碼,其它就是作為點綴了。完成這三步,一個簡單的上傳即實現了。

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("http://", "/");   //Servlet初始化時執行,如果上傳文件目錄不存在則自動創建   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", "上傳失敗,請確認上傳的文件存在并且類型是圖片!");       request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request,         response);      }     }    }   } catch (Exception e) {    e.printStackTrace();    request.setAttribute("errorMsg", "上傳失敗,請確認上傳的文件大小不能超過"+sizeMax+"M");    request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request,      response);   }     } 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 莲花县| 湄潭县| 永登县| 黔东| 大埔区| 如东县| 乌兰察布市| 讷河市| 新邵县| 克拉玛依市| 本溪| 嘉峪关市| 巴彦县| 阿拉善右旗| 舟山市| 阳城县| 南华县| 通城县| 金湖县| 信阳市| 晋江市| 澄城县| 江源县| 大新县| 色达县| 海南省| 富阳市| 元氏县| 航空| 奇台县| 华坪县| 电白县| 沁阳市| 通化县| 伊通| 苏尼特右旗| 金寨县| 沂水县| 天祝| 明溪县| 房产|