Java組件commons fileupload完成文件上傳功效。本站提示廣大學習愛好者:(Java組件commons fileupload完成文件上傳功效)文章只能為提供參考,不一定能成為您想要的結果。以下是Java組件commons fileupload完成文件上傳功效正文
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 ><base target="_self"></span>
<title>書本圖片上傳</title>
</head>
<body>
<h5>圖片上傳</h5><hr/>
<p >${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("\\", "/");
//Servlet初始化時履行,假如上傳文件目次不存在則主動創立
if(!new File(serverPath+uploadPath).isDirectory()){
new File(serverPath+uploadPath).mkdirs();
}
if(!new File(serverPath+tempPath).isDirectory()){
new File(serverPath+tempPath).mkdirs();
}
<span >DiskFileItemFactory factory = new DiskFileItemFactory();</span>
factory.setSizeThreshold(5*1024); //最年夜緩存
factory.setRepository(new File(serverPath+tempPath));//暫時文件目次
<span >ServletFileUpload upload = new ServletFileUpload(factory);</span>
upload.setSizeMax(sizeMax*1024*1024);//文件最年夜下限
String filePath = null;
try {
<span >List<FileItem> items = upload.parseRequest(request);</span>//獲得一切文件列表
for (FileItem item : items) {
//取得文件名,這個文件名包含途徑
<span >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 >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);
}
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。