JavaWeb文件上傳下載功能示例解析
在Web應(yīng)用系統(tǒng)開(kāi)發(fā)中,文件上傳和下載功能是非常常用的功能,今天來(lái)講一下JavaWeb中的文件上傳和下載功能的實(shí)現(xiàn)。
1. 上傳簡(jiǎn)單示例
Jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>文件上傳下載</title> </head> <body> <form action="${pageContext.request.contextPath}/UploadServlet" enctype="multipart/form-data" method="post"> 上傳用戶:<input type="text" name="username" /> <br /> 上傳文件1:<input type="file" name="file1" /> <br /> 上傳文件2:<input type="file" name="file2" /> <br /> <input type="submit" value="上傳 "/> </form> <br /> ${requestScope.message} </body> </html>
Servlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try{ //1.得到解析器工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2.得到解析器 ServletFileUpload upload = new ServletFileUpload(factory); //3.判斷上傳表單的類型 if(!upload.isMultipartContent(request)){ //上傳表單為普通表單,則按照傳統(tǒng)方式獲取數(shù)據(jù)即可 return; } //為上傳表單,則調(diào)用解析器解析上傳數(shù)據(jù) List<FileItem> list = upload.parseRequest(request); //FileItem //遍歷list,得到用于封裝第一個(gè)上傳輸入項(xiàng)數(shù)據(jù)fileItem對(duì)象 for(FileItem item : list){ if(item.isFormField()){ //得到的是普通輸入項(xiàng) String name = item.getFieldName(); //得到輸入項(xiàng)的名稱 String value = item.getString(); System.out.println(name + "=" + value); }else{ //得到上傳輸入項(xiàng) String filename = item.getName(); //得到上傳文件名 C:\Documents and Settings\ThinkPad\桌面\1.txt filename = filename.substring(filename.lastIndexOf("\\")+1); InputStream in = item.getInputStream(); //得到上傳數(shù)據(jù) int len = 0; byte buffer[]= new byte[1024]; //用于保存上傳文件的目錄應(yīng)該禁止外界直接訪問(wèn) String savepath = this.getServletContext().getRealPath("/WEB-INF/upload"); System.out.println(savepath); FileOutputStream out = new FileOutputStream(savepath + "/" + filename); //向upload目錄中寫(xiě)入文件 while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close(); request.setAttribute("message", "上傳成功"); } } }catch (Exception e) { request.setAttribute("message", "上傳失敗"); e.printStackTrace(); } }
2. 修改后的上傳功能:
注意事項(xiàng):
1、上傳文件名的中文亂碼和上傳數(shù)據(jù)的中文亂碼
upload.setHeaderEncoding("UTF-8"); //解決上傳文件名的中文亂碼
//表單為文件上傳,設(shè)置request編碼無(wú)效,只能手工轉(zhuǎn)換
1.1 value = new String(value.getBytes("iso8859-1"),"UTF-8");
1.2 String value = item.getString("UTF-8");
2.為保證服務(wù)器安全,上傳文件應(yīng)該放在外界無(wú)法直接訪問(wèn)的目錄
3、為防止文件覆蓋的現(xiàn)象發(fā)生,要為上傳文件產(chǎn)生一個(gè)唯一的文件名
4、為防止一個(gè)目錄下面出現(xiàn)太多文件,要使用hash算法打散存儲(chǔ)
5.要限制上傳文件的最大值,可以通過(guò):ServletFileUpload.setFileSizeMax(1024)方法實(shí)現(xiàn),并通過(guò)捕獲:
FileUploadBase.FileSizeLimitExceededException異常以給用戶友好提示
6.想確保臨時(shí)文件被刪除,一定要在處理完上傳文件后,調(diào)用item.delete方法
7.要限止上傳文件的類型:在收到上傳文件名時(shí),判斷后綴名是否合法
8、監(jiān)聽(tīng)文件上傳進(jìn)度:
ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("文件大小為:" + pContentLength + ",當(dāng)前已處理:" + pBytesRead); } });
9. 在web頁(yè)面中動(dòng)態(tài)添加文件上傳輸入項(xiàng)
function addinput(){ var div = document.getElementById("file"); var input = document.createElement("input"); input.type="file"; input.name="filename"; var del = document.createElement("input"); del.type="button"; del.value="刪除"; del.onclick = function d(){ this.parentNode.parentNode.removeChild(this.parentNode); } var innerdiv = document.createElement("div"); innerdiv.appendChild(input); innerdiv.appendChild(del); div.appendChild(innerdiv); }
上傳jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'upload2.jsp' starting page</title> <script type="text/javascript"> function addinput(){ var div = document.getElementById("file"); var input = document.createElement("input"); input.type="file"; input.name="filename"; var del = document.createElement("input"); del.type="button"; del.value="刪除"; del.onclick = function d(){ this.parentNode.parentNode.removeChild(this.parentNode); } var innerdiv = document.createElement("div"); innerdiv.appendChild(input); innerdiv.appendChild(del); div.appendChild(innerdiv); } </script> </head> <body> <form action="" enctype="mutlipart/form-data"></form> <table> <tr> <td>上傳用戶:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>上傳文件:</td> <td> <input type="button" value="添加上傳文件" onclick="addinput()"> </td> </tr> <tr> <td></td> <td> <div id="file"> </div> </td> </tr> </table> </body> </html>
上傳servlet
public class UploadServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request.getParameter("username"); //****錯(cuò)誤 request.setCharacterEncoding("UTF-8"); //表單為文件上傳,設(shè)置request編碼無(wú)效 //得到上傳文件的保存目錄 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); try{ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/temp"))); ServletFileUpload upload = new ServletFileUpload(factory); /*upload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("文件大小為:" + pContentLength + ",當(dāng)前已處理:" + pBytesRead); } });*/ upload.setHeaderEncoding("UTF-8"); //解決上傳文件名的中文亂碼 if(!upload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } /*upload.setFileSizeMax(1024); upload.setSizeMax(1024*10);*/ List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ if(item.isFormField()){ //fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù) String name = item.getFieldName(); String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{ //fileitem中封裝的是上傳文件 String filename = item.getName(); //不同的瀏覽器提交的文件是不一樣 c:\a\b\1.txt 1.txt System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } filename = filename.substring(filename.lastIndexOf("\\")+1); InputStream in = item.getInputStream(); String saveFilename = makeFileName(filename); //得到文件保存的名稱 String realSavePath = makePath(saveFilename, savePath); //得到文件的保存目錄 FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename); byte buffer[] = new byte[1024]; int len = 0; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close(); item.delete(); //刪除臨時(shí)文件 } } }catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "文件超出最大值!??!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } catch (Exception e) { e.printStackTrace(); } } public String makeFileName(String filename){ //2.jpg return UUID.randomUUID().toString() + "_" + filename; } public String makePath(String filename,String savePath){ int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5 File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3. 下載功能
//列出網(wǎng)站所有下載文件 public class ListFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filepath = this.getServletContext().getRealPath("/WEB-INF/upload"); Map map = new HashMap(); listfile(new File(filepath),map); request.setAttribute("map", map); request.getRequestDispatcher("/listfile.jsp").forward(request, response); } public void listfile(File file,Map map){ if(!file.isFile()){ File files[] = file.listFiles(); for(File f : files){ listfile(f,map); } }else{ String realname = file.getName().substring(file.getName().indexOf("_")+1); //9349249849-88343-8344_阿_凡_達(dá).avi map.put(file.getName(), realname); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
jsp顯示
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'listfile.jsp' starting page</title> </head> <body> <c:forEach var="me" items="${map}"> <c:url value="/servlet/DownLoadServlet" var="downurl"> <c:param name="filename" value="${me.key}"></c:param> </c:url> ${me.value } <a href="${downurl}">下載</a> <br/> </c:forEach> </body> </html>
下載處理servlet
public class DownLoadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("filename"); //23239283-92489-阿凡達(dá).avi filename = new String(filename.getBytes("iso8859-1"),"UTF-8"); String path = makePath(filename,this.getServletContext().getRealPath("/WEB-INF/upload")); File file = new File(path + "\\" + filename); if(!file.exists()){ request.setAttribute("message", "您要下載的資源已被刪除?。?); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } String realname = filename.substring(filename.indexOf("_")+1); response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); FileInputStream in = new FileInputStream(path + "\\" + filename); OutputStream out = response.getOutputStream(); byte buffer[] = new byte[1024]; int len = 0; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } in.close(); out.close(); } public String makePath(String filename,String savePath){ int hashcode = filename.hashCode(); int dir1 = hashcode&0xf; //0--15 int dir2 = (hashcode&0xf0)>>4; //0-15 String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5 File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java超過(guò)long類型的數(shù)據(jù)表示方法
這篇文章主要給大家介紹Java超過(guò)long類型的數(shù)據(jù)如何表示,在 Java 中,如果需要表示超過(guò) long 類型范圍的數(shù)據(jù),可以使用 BigInteger 類,BigInteger 是 Java 提供的一個(gè)用于處理任意精度整數(shù)的類,它可以表示非常大或非常小的整數(shù),需要的朋友可以參考下2023-09-09IDEA報(bào)錯(cuò):Unable to save settings Failed to save settings
這篇文章主要介紹了IDEA報(bào)錯(cuò):Unable to save settings Failed to save settings的相關(guān)知識(shí),本文給大家分享問(wèn)題原因及解決方案,需要的朋友可以參考下2020-09-09如何使用ThreadLocal上下文解決查詢性能問(wèn)題
這篇文章主要介紹了利用ThreadLocal上下文解決查詢性能問(wèn)題,有兩種解決方案,一種是使用ThreadLocal上下文,另一種是使用Redis緩存,需要的朋友可以參考下2023-07-07SpringBoot?攔截器返回false顯示跨域問(wèn)題
這篇文章主要介紹了SpringBoot?攔截器返回false顯示跨域問(wèn)題,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,需要的小伙伴可以參考一下2022-04-04Java 客戶端向服務(wù)端上傳mp3文件數(shù)據(jù)的實(shí)例代碼
這篇文章主要介紹了Java 客戶端向服務(wù)端上傳mp3文件數(shù)據(jù)的實(shí)例代碼,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09解決@RequestBody使用不能class類型匹配的問(wèn)題
這篇文章主要介紹了解決@RequestBody使用不能class類型匹配的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07