JSP使用Common FileUpload組件實(shí)現(xiàn)文件上傳及限制上傳類型實(shí)例代碼
1、將commons-fileupload-1.3.3.jar復(fù)制到Web應(yīng)用的lib文件夾下,在WebRoot目錄下創(chuàng)建limit.jsp頁面,在該頁面中添加一個文件域的表單,設(shè)置類型為 multipart/form-data。代碼如下:
<body>
<h2>上傳圖書課件</h2>
<form action="LimitFile" name="one" enctype="multipart/form-data" method="post">
選擇一個rar文件:
<input type="file" name="fileupload" value="upload" />
<input type="submit" value="上傳"> <input type="reset" value="取消">
</form>
</body>
上述代碼指定提交后將請求提交給LimitFile處理,LimitFile(Servlet)用來處理上傳文件及判斷文件類型是否匹配,顯示上傳結(jié)果。
2、創(chuàng)建名為LimitFile的Servlet,并在doPost()方法中編寫實(shí)現(xiàn)代碼,如下所示:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uploadpath = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
//設(shè)置是否使用臨時文件保存解析出來的數(shù)據(jù)的那個臨界值,該方法傳入?yún)?shù)的單位是字節(jié)。
factory.setSizeThreshold(30 * 1024);
//用于設(shè)置setSizeThreshold()方法中提到的臨時文件的存放目錄,這里要求使用絕對路徑。
factory.setRepository(factory.getRepository());
ServletFileUpload upload = new ServletFileUpload(factory);
List list = null;
try{
list = upload.parseRequest(request);
String[] limit = new String[]{".jpg", ".gif", ".png", ".bmp"};
//定義限制的文件類型
SuffixFileFilter filter = new SuffixFileFilter(limit);
//獲取SuffixFileFilter實(shí)例
Iterator iterator = list.iterator();
while(iterator.hasNext()){
FileItem item =(FileItem)iterator.next();
if(!item.isFormField()){
String filePath = item.getName();
if(filePath != null){
File filename= new File(filePath);
File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");
uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;
//因?yàn)槁窂胶竺娑嗔藗€";"號,所以要去掉
uploadpath = uploadpath.substring(0, uploadpath.length()-1);
File saveFile = new File(uploadpath,filename.getName());
boolean flag = filter.accept(saveFile);
if(flag){
out.print("禁止上傳傳圖片文件");
break;
}else{
try {
item.write(saveFile);
out.print("文件上傳成功");
} catch (Exception e) {
out.print("文件上傳失敗了");
e.printStackTrace();
}
}
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
}
}
上述代碼在字節(jié)串?dāng)?shù)組limit中定義了不允許上傳的文件類型,然后將該數(shù)組傳遞給SuffixFileFilter類的構(gòu)造函數(shù)。在通過該類的accept()方法驗(yàn)證當(dāng)前上傳的文件是否符合條件。最后將文件保存到項(xiàng)目的upload目錄下。
總結(jié)
以上所述是小編給大家介紹的JSP使用Common FileUpload組件實(shí)現(xiàn)文件上傳及限制上傳類型實(shí)例代碼,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!
相關(guān)文章
JSP實(shí)現(xiàn)用于自動生成表單標(biāo)簽html代碼的自定義表單標(biāo)簽
這篇文章主要介紹了JSP實(shí)現(xiàn)用于自動生成表單標(biāo)簽html代碼的自定義表單標(biāo)簽,可實(shí)現(xiàn)自動生成html標(biāo)簽的功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10
從textarea中獲取數(shù)據(jù)之后按原樣顯示實(shí)現(xiàn)代碼
從textarea中獲取數(shù)據(jù),按原樣顯示在某些特殊的情況下還是比較使實(shí)用的,下面為大家分享下實(shí)現(xiàn)代碼,感興趣的朋友可以參考下,希望對你有所幫助2013-04-04
J2ME/J2EE實(shí)現(xiàn)用戶登錄交互 實(shí)現(xiàn)代碼
用手機(jī)客戶端進(jìn)行登錄服務(wù)器,然后返回消息進(jìn)行交互.2009-07-07

