Apache提供的commons-fileupload jar包實現 文件上傳 確實很簡單,最近要用Servlet/JSP做一個圖片上傳功能,在網上找了很多資料,大多是基于struts框架介紹的,還有些雖然也介紹common-fileupload的上傳,但是那些例子比較老,有些類現在都廢棄了。通過研究學習總結,終于完成了這個上傳功能,下面與大家分享一下。
?
?
- 案例場景
- 實現效果
?
點擊“上傳圖片”按鈕,通過模式窗口彈出上傳界面,如下圖所示。
?
通過“瀏覽”按鈕選擇指定圖片,點擊“上傳”按鈕進行上傳,如果上傳成功則彈出成功提示,用戶點擊“確定”后關閉彈出窗并自動將新圖片顯示在頁面上,如下圖所示。
?
?
- 代碼實現
<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>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<meta http-equiv="pragma" content="no-cache" />
<base target="_self">
<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>
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();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(5*1024); //最大緩存
factory.setRepository(new File(serverPath+tempPath));//臨時文件目錄
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(sizeMax*1024*1024);//文件最大上限
String filePath = null;
try {
List<FileItem> items = upload.parseRequest(request);
//獲取所有文件列表
for (FileItem item : items) {
//獲得文件名,這個文件名包括路徑
if(!item.isFormField()){
//文件名
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("."));
item.write(new File(filePath));
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);
}
}
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

