commons-fileupload實現上傳——JAVA
在許多Web站點應用中都需要為使用者提供通過瀏覽器上傳文件資料的功能,例如,上傳個人相片、共享資料等。在DRP中,就有這個一個功能,需要將對應的物料圖片上傳並顯示。
對於上傳功能,其實在瀏覽器端提供了很好的支援,只需在Web伺服器端獲取瀏覽器上傳檔案並儲存。為了簡化和幫助Web開發人員接收瀏覽器上傳的檔案,一些公司和組織專門開發了檔案上傳元件,比如說commons-fileupload,現在就看看這個功能是怎麼實現的。
需求:對應的物料圖片上傳並顯示
引入jar包:
首先要引入兩個jar包,一個是commons-fileupload.jar包,另一個是commons-io-2.2.jar包。
瀏覽器端如何支援:
採用post提交;
更改form的enctype屬性為:enctype="multipart/form-data",即:
關於將上傳的圖片儲存在什麼地方的問題,我覺得這兩種方法挺好:<form name="itemForm" target="_self" id="itemForm" method="post" action="servlet/item/FileUploadServlet" enctype="multipart/form-data"> <span style="white-space:pre"> </span><input name="btn_upload" class="button1" type="submit" id="btn_upload" value="上傳"><span style="white-space:pre"> </span> </form>
第一種:圖片儲存到本地磁碟。圖片的名稱對應物料編號。
第二種:圖片儲存到本地磁碟,同時在資料庫中儲存此圖片名。
兩種方法大同小異,詳細介紹第二種方法。
例項:
圖片儲存到本地磁碟,同時在資料庫中儲存此圖片名。
item_upload.jsp中
<%
<span style="white-space:pre"> </span>Item item=(Item)request.getAttribute("item"); //獲取request中的值
%>
在Servlet中完成檔案上傳及將圖片寫到相應目錄並在資料庫中儲存此圖片名稱:<form name="itemForm" target="_self" id="itemForm" method="post" action="servlet/item/FileUploadServlet" enctype="multipart/form-data"> <input type="hidden" id="itemNo" name="itemNo" value=<%=item.getItemNo() %>> <div align="center"> <table width="95%" border="0" cellspacing="2" cellpadding="2"> <tr> <td> </td> </tr> </table> <table width="95%" border="0" cellspacing="0" cellpadding="0" height="8"> <tr> <td width="522" class="p1" height="2" nowrap> <img src="images/mark_arrow_03.gif" width="14" height="14"> <b>基礎資料管理>>物料維護>>上傳物料圖片</b> </td> </tr> </table> <hr width="97%" align="center" size=0> <table width="95%" border="0" cellpadding="0" cellspacing="0"> <tr> <td height="29"> <div align="right"> 物料程式碼: </div> </td> <td> <%=item.getItemNo() %> </td> </tr> <tr> <td height="74"> <div align="right"> 圖片: </div> </td> <span style="white-space:pre"> </span><td> <img src="Upload/<%=item.getFileName() %>" width="85" height="49"> </td> </tr> <tr> <td width="22%" height="29"> <div align="right"> <font color="#FF0000">*</font>選擇圖片: </div> </td> <td width="78%"> <input name="fileName" type="file" class="text1" size="40" maxlength="40"> </td> </tr> </table> <hr width="97%" align="center" size=0> <div align="center"> <input name="btn_upload" class="button1" type="submit" id="btn_upload" value="上傳"> <input name="btnBack" class="button1" type="button" id="btnBack" value="返回" onClick="history.go(-1)"> </div> </div> </form>
public class FileUploadServlet extends HttpServlet {
File uploadPath=null;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取物料資訊
ItemManager itemManager=new ItemManagerImpl();
String itemNo=request.getParameter("itemNo");
Item item=itemManager.findItemById(itemNo);//查詢該物料所有資訊
request.setAttribute("item",item);
request.getRequestDispatcher("/basedata/item_upload.jsp").forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//String uploadPath="C:\\Users\\ZhuDan\\Desktop\\Drp\\DRP系統\\apache-tomcat-7.0.6\\webapps\\drp3.9\\Upload";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
ItemManager itemManager=new ItemManagerImpl();
String itemNo="";
String fileName="";
if(isMultipart==true){
try{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);//得到所有的檔案
Iterator<FileItem> itr = items.iterator();
while(itr.hasNext()){//依次處理每個檔案
FileItem item=(FileItem)itr.next();//獲取每個檔案的所有資訊
//是普通的表單型別
if(item.isFormField()){
if("itemNo".equals(item.getFieldName())){
itemNo=item.getString();
}
}
fileName=item.getName();//獲得檔名,包括路徑 D:\生活\照片\Friends\蹄蹄\高饒珊.jpg
if(fileName!=null){
File fullFile=new File(item.getName());
//要存入資料夾的路徑
File savedFile=new File(uploadPath,fullFile.getName());
//擷取字串 如:C:\WINDOWS\Debug\PASSWD.LOG
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
if(itemNo!=null && fileName!=null){
itemManager.uploadItemImage(itemNo, fileName);
}
//存入資料夾
item.write(savedFile);
// File fullFile=new File(itemNo);
// File savedFile=new File(uploadPath,fullFile.getName()+".jpg");
}
}
// System.out.print("upload succeed");
}
catch(Exception e){
e.printStackTrace();
}
finally{
response.sendRedirect("QueryServlet");
}
}
}
public void init() throws ServletException{
uploadPath=new File(getServletContext().getRealPath("Upload"));//獲取用於儲存圖片的Upload資料夾的路徑
if(!uploadPath.exists()){ //如果不存在Upload資料夾,則建立
uploadPath.mkdir();
}
}
}
介面效果如下:
資料庫中欄位:
對應的本地資料夾(tomcat)中:
總結:
原理如下: FileUpload元件將頁面提交的所有元素(普通form表單域,如input和檔案域file)都看作一樣的FileItem,這樣上傳頁面提交的 request請求也就是一個FileItem的有序組合,FileUpload元件可以解析該request,並返回一個一個的FileItem。而對 每一個FileItem,FileUpload元件可以判斷出它是普通form表單域還是檔案file域,從而根據不同的型別,採取不同的操作--如果是表單域,就讀出其值,如果是檔案域,就儲存檔案到伺服器硬碟上或者記憶體中。