您好,登錄后才能下訂單哦!
利用servlet怎么實現一個文件上傳下載功能?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
一、準備工作:
1.1 文件上傳插件:uploadify;
1.2 文件上傳所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar
1.3 將數據轉成JSON對象需要jar包:commons-beanutils-1.8.3.jar、commons-collections-3.2.1.jar、commons-lang-2.6.jar、commons-logging-1.1.3.jar、ezmorph-1.0.6.jar和json-lib-2.4-jdk15.jar
1.4 開發工具:我用的是Eclipse,隨意
1.5 目錄結構
需要注意的是:變更uploadify.css文件中的取消文件上傳圖片的路徑
.uploadify-queue-item .cancel a { background: url('../images/uploadify-cancel.png') 0 0 no-repeat; float: right; height: 16px; text-indent: -9999px; width: 16px; }
二、代碼展示
2.1 客戶端代碼設計
JSP部分
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>演示-操作文件</title> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <script type="text/javascript" src="<c:url value="/js/jquery-1.11.2.min.js"/>"></script> <script type="text/javascript" src="<c:url value="/uploadify/js/jquery.uploadify-3.2.1.min.js"/>"></script> <link href="<c:url value=" rel="external nofollow" /uploadify/css/uploadify.css"/>" type="text/css" rel="stylesheet"/> <script type="text/javascript">var baseUrl = '<%=request.getContextPath()%>';</script> <script type="text/javascript" src="<c:url value="/index.js"/>"></script> <style type="text/css"> /* 上傳、取消上傳按鈕style start */ .Button { width: 80px; margin: 3px 1px 0 5px; padding: 0 10px; background-color: #16a0d3; border: none; display: inline-block; font-family: "Microsoft Yahei"; font-size: 14px; cursor: pointer; height: 30px; line-height: 30px; color: #FFF; border-radius: 5px; text-decoration:none; text-align:center; } .ButtonOver { width: 80px; margin: 3px 1px 0 5px; padding: 0 10px; background-color: #117ea6; border: none; display: inline-block; font-family: "Microsoft Yahei"; font-size: 14px; cursor: pointer; height: 30px; line-height: 30px; color: #FFF; border-radius: 5px; text-decoration:none; text-align:center; } /* end 上傳、取消上傳按鈕style */ </style> </head> <body> <!-- 文件上傳 --> <div id="file_upload"></div> <div id="ctrlUpload" > <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('#file_upload').uploadify('upload', '*');" class="Button" onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'"> 上傳所有 </a> <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('#file_upload').uploadify('cancel', '*');$('#ctrlUpload').hide();" class="Button" onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'"> 取消上傳 </a> </div> <table border=1 id="tableFiles"> <thead> <th>序號</th> <th>文件名</th> <th>文件預覽</th> <th>文件下載</th> <th>文件刪除</th> </thead> <tbody></tbody> </table> </body> </html>
js文件
var operateFile = new OperateFile(); window.onload = function() { operateFile.init(); } /** * 對文件進行操作 * @returns */ function OperateFile() { var object = this; /** * 初始化操作: */ this.init = function() { // 隊列中的文件數 var selectedCount = 0; $('#file_upload').uploadify({ 'method' : 'get',// 默認值post,設置成get是為了向后臺傳遞自定義的參數 'auto' : false,// 設置為true當選擇文件后就直接上傳了,為false需要點擊上傳按鈕才上傳。默認值為TRUE 'buttonText' : '添加文件',// 按鈕文本 'fileTypeExts' : '*.gif; *.jpg; *.png;*.pdf;*.zip;',// 限制上傳文件類型,默認值沒有限制(*.*) 'fileTypeDesc' : '請選擇gif jpg png pdf zip類型的文件',// 這個屬性值必須設置fileTypeExts屬性后才有效,用來設置選擇文件對話框中的提示文本,默認值:All Files 'swf' : baseUrl + '/uploadify/flash/uploadify.swf', // flash文件路徑(幫助我們與后端交互數據) 'uploader' : baseUrl + '/uploadFile.do' , // 處理文件上傳請求地址 'formData' : {'param1':'測試文件上傳'},// 請求參數:上傳每個文件的同時提交到服務器的額外數據 'onDialogClose' : function(queueData) { // 獲取該隊列中有多少個要上傳的文件 var queueSize = $('#file_upload-queue').children('div').length; if (queueSize > 0) { $('#ctrlUpload').show(); } }, 'onUploadSuccess' : function(file, data, response) {// 上傳成功 // 將josn字符串轉換成JSON對象 data = eval('(' + data + ')'); // 獲取頁面上文件展示table 有多少行 var rowsLength = $('#tableFiles')[0].rows.length; // 設置查看文件所需參數 var param = "fileName=" + data.fileName; // 查看文件請求地址 var viewUrl = baseUrl + '/viewFile.do?' + param; // 下載文件請求地址 var downloadUrl = baseUrl + '/downloadFile.do?' + param; // 拼接一行tr var trTemplate = '<tr>' + '<td>' + rowsLength + '</td>' + '<td>' + file.name // 仍展示原文件名 + '</td>' + '<td>' + '<a href="' + viewUrl + '" rel="external nofollow" target="_blank">點擊預覽</a>' + '<input type="hidden" name="imgAddress" value="' + data.fileName + '"/>' + '</td>' + '<td>' + '<a href="' + downloadUrl + '" rel="external nofollow" >點擊下載</a>' + '</td>' + '<td>' + '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="operateFile.deleteFile(\'' + data.fileName + '\',' + rowsLength +');">點擊刪除</a>' + '</td>' +'</tr>'; $('#tableFiles').append(trTemplate); }, 'onUploadError' : function(file, errorCode, errorMsg, errorString) {// 上傳失敗 } }); } /** * 刪除文件 * @param 文件名 */ this.deleteFile = function(fileName,rowIndex) { // 設置刪除文件所需參數 var param = "fileName=" + fileName; // 刪除文件請求地址 var deleteUrl = baseUrl + '/deleteFile.do?' + param; $.get( deleteUrl, function(msg) { alert(msg); if ("刪除失敗!" != msg) { // 刪除該行記錄 $('#tableFiles')[0].deleteRow(rowIndex); } } ); } }
2.2 服務器端代碼設計
文件上傳代碼(FileUpload.javae文件)
package controller.fileHandler; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import net.sf.json.JSONObject; public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * 處理文件上傳的post * @precaution 下方的類名出自包import org.apache.commons.fileupload.* */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.設置參數編碼 request.setCharacterEncoding("UTF-8"); // 設置響應數據字符集 response.setCharacterEncoding("UTF-8"); // 設置響應數據格式 // response.setContentType("application/json; charset=UTF-8"); PrintWriter out = response.getWriter(); // 2.創建文件上傳處理工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 3.設置臨時文件存放地點 // 3.1獲取當前web應用程序對象(WEB容器在啟動時,它會為每個WEB應用程序都創建一個對應的ServletContext對象,它代表當前web應用) ServletContext servletContext = this.getServletConfig().getServletContext(); // 3.2獲取服務器的臨時目錄(tomcat、WebLogic) // D:\ProgramFiles(x86)\APACHE\TOMCAT\apache-tomcat-7.0.40-x86\work\Catalina\localhost\demo File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); // 3.3臨時文件將會存儲在該目錄下 factory.setRepository(repository); // 4.創建文件上傳處理器 ServletFileUpload upload = new ServletFileUpload(factory); // 5.判斷請求類型是否為文件上傳類型 boolean multipartContent = upload.isMultipartContent(request); Map<String, String> mapData = new HashMap<String, String>(); // 返回信息 String msg = ""; // 錯誤信息 String errorMsg = ""; // 文件名 String fileName = ""; if (multipartContent) { try { // 獲取請求參數 String param = request.getParameter("param1"); System.out.println(param); // 6.解析請求信息 List<FileItem> items = upload.parseRequest(request); // 7.對所有請求信息進行判斷 Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); // 信息為文件格式 if (!item.isFormField()) { fileName = processUploadedFile(param, item); msg = "上傳成功!"; } } } catch (FileUploadException e) { e.printStackTrace(); msg = "上傳失敗!"; errorMsg = e.getMessage(); } } else { msg = "form表單類型不是multipart/form-data,無法上傳!"; } mapData.put("msg", msg); mapData.put("errorMsg", errorMsg); mapData.put("fileName", fileName); // 將Map轉成JSON JSONObject jsonData = JSONObject.fromObject(mapData); // 返回客戶端信息 out.print(jsonData.toString()); } /** * 處理上傳的文件 * @param ORG_ID * @param order * @param item */ @SuppressWarnings("unused") private String processUploadedFile(String param, FileItem item) { // Process a file upload String fieldName = item.getFieldName();// 默認值為Filedata // 獲取文件名 String fileName = item.getName(); // 內容類型:application/octet-stream String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); // 獲取文件大小 long sizeInBytes = item.getSize(); // 1.指定文件上傳的根路徑 String path = this.getServletContext().getRealPath("/WEB-INF/uploadFiles"); // 2.路徑構成:/uploadfile/fileName // TODO 可以自定義文件存放路徑 // 3.根據路徑批量創建文件夾 File fileDirectories = new File(path); // 目錄不存在時,再創建 if (!fileDirectories.exists()) { fileDirectories.mkdirs();// 所有的文件夾都創建成功才返回TRUE } // 4.文件名格式校驗(文件名中不能包含#號) int index = fileName.indexOf("#"); if (index > -1) { fileName = fileName.replace('#', '_'); } // TODO 可以對文件名進行重命名 // 5.在指定路徑下創建指定名稱的文件 File uploadedFile = new File(path + "/" + fileName); // 6.判斷該文件是否已存在 if (!uploadedFile.exists()) { try { // 使用了這個方法寫入文件,臨時文件會被系統自動刪除 item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } } // 返回重名后的文件名 return fileName; } /** * 處理信息為普通的格式 * @param item */ private void processFormField(FileItem item) { // Process a regular form field if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); } } }
文件查看代碼(FileView.java文件)
package controller.fileHandler; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileView extends HttpServlet { private static final long serialVersionUID = 1L; // 設定輸出的類型 private static final String GIF = "image/gif;charset=UTF-8"; private static final String JPG = "image/jpeg;charset=UTF-8"; private static final String PNG = "image/png;charset=UTF-8"; private static final String PDF = "application/pdf;charset=UTF-8"; private static final String ZIP = "application/zip;charset=UTF-8"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * 處理文件查看的post * @throws IOException * @precaution 下方的類名出自包import org.apache.commons.fileupload.* */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 文件流 InputStream is = null; // 輸入緩沖流 BufferedInputStream bis = null; // 得到輸出流 OutputStream output = null; // 輸出緩沖流 BufferedOutputStream bos = null; // 1.設置參數編碼 request.setCharacterEncoding("UTF-8"); // 2.設置響應數據字符集 response.setCharacterEncoding("UTF-8"); // 3.獲取客戶端請求參數:文件名 String fileName = request.getParameter("fileName"); // 4.重置response response.reset(); // 5.設置響應數據格式 if (fileName.endsWith(".gif")) { response.setContentType(GIF); } else if (fileName.endsWith(".jpg")) { response.setContentType(JPG); } else if (fileName.endsWith(".png")) { response.setContentType(PNG); } else if (fileName.endsWith(".pdf")) { response.setContentType(PDF); } else if (fileName.endsWith(".gif")) { response.setContentType(GIF); } else if (fileName.endsWith(".zip")) { response.setContentType(ZIP); } String filePath = "WEB-INF/uploadFiles/" + fileName; // 獲取當前web應用程序 ServletContext webApp = this.getServletContext(); // 6.獲取指定文件上傳的真實路徑 filePath = webApp.getRealPath(filePath); // 7.讀取目標文件,通過response將目標文件寫到客戶端 is = new FileInputStream(filePath); bis = new BufferedInputStream(is); output = response.getOutputStream(); bos = new BufferedOutputStream(output); byte data[] = new byte[1024];// 緩沖字節數 int size = bis.read(data); while (size != -1) { bos.write(data, 0, size); size = bis.read(data); } // 關閉流 bis.close(); bos.flush();// 清空輸出緩沖流 bos.close(); output.close(); } }
文件下載代碼(FileDownload.java文件)
package controller.fileHandler; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileDownload extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * 處理文件下載的post * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.設置參數編碼 request.setCharacterEncoding("UTF-8"); // 設置響應數據字符集 response.setCharacterEncoding("UTF-8"); // 1.獲得請求文件名 String fileName = request.getParameter("fileName"); // 2.設置文件MIME類型(指定要返回內容的類型) response.setContentType(getServletContext().getMimeType(fileName)); // 3.設置Content-Disposition(指定下載該文件時的文件名) response.setHeader("content-disposition", "attachment;filename=" + fileName); // 4.讀取目標文件,通過response將目標文件寫到客戶端 // 4.1 獲取目標文件的絕對路徑 String filePath = "WEB-INF/uploadFiles/" + fileName; filePath = this.getServletContext().getRealPath(filePath); // 4.2 讀取文件 InputStream in = new FileInputStream(filePath); // 4.3 輸出文件 OutputStream out = response.getOutputStream(); // 寫文件 int n; while ((n = in.read()) != -1) { out.write(n); } in.close(); out.close(); } }
文件刪除代碼(FileDelete.java文件)
package controller.fileHandler; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileDelete extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * 處理文件下載的post * @throws IOException */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.設置參數編碼 request.setCharacterEncoding("UTF-8"); // 設置響應數據字符集 response.setCharacterEncoding("UTF-8"); // 2.獲得請求文件名 String fileName = request.getParameter("fileName"); // 3.獲取該文件所在路徑 String filePath = "WEB-INF/uploadFiles/" + fileName; filePath = this.getServletContext().getRealPath(filePath); // 4.在指定路徑下創建指定名稱的文件 File deleteFile = new File(filePath); boolean flag = false; String msg = ""; // 5.判斷該文件是否已存在 if (deleteFile.exists()) { flag = deleteFile.delete(); if (flag) { msg = "刪除成功!"; } else { msg = "刪除失敗!"; } } else { msg = "該文件不存在!"; } // 6.返回客戶端操作信息 response.getWriter().print(msg); } }
web.xml代碼
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>demo_uploadAndDownload</display-name> <context-param> <param-name>webAppRootKey</param-name> <param-value>uploadAndDownload</param-value> </context-param> <!-- 處理文件的Servlet --> <!-- 文件上傳 Start --> <servlet> <servlet-name>upload</servlet-name> <!-- 配置處理文件上傳的java類 --> <servlet-class>controller.fileHandler.FileUpload</servlet-class> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <!-- 設置文件上傳請求路徑 --> <url-pattern>/uploadFile.do</url-pattern> </servlet-mapping> <!-- End 文件上傳 --> <!-- 文件預覽 Start --> <servlet> <servlet-name>view</servlet-name> <!-- 配置處理文件預覽的java類 --> <servlet-class>controller.fileHandler.FileView</servlet-class> </servlet> <servlet-mapping> <servlet-name>view</servlet-name> <!-- 設置文件預覽請求路徑 --> <url-pattern>/viewFile.do</url-pattern> </servlet-mapping> <!-- End 文件預覽 --> <!-- 文件下載 Start --> <servlet> <servlet-name>download</servlet-name> <!-- 配置處理文件下載的java類 --> <servlet-class>controller.fileHandler.FileDownload</servlet-class> </servlet> <servlet-mapping> <servlet-name>download</servlet-name> <!-- 設置文件下載請求路徑 --> <url-pattern>/downloadFile.do</url-pattern> </servlet-mapping> <!-- End 文件下載 --> <!-- 文件刪除 Start --> <servlet> <servlet-name>delete</servlet-name> <!-- 配置處理文件刪除的java類 --> <servlet-class>controller.fileHandler.FileDelete</servlet-class> </servlet> <servlet-mapping> <servlet-name>delete</servlet-name> <!-- 設置文件刪除請求路徑 --> <url-pattern>/deleteFile</url-pattern> </servlet-mapping> <!-- End 文件刪除 --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
2.3 代碼優化
處理文件查看(FileView.java) ,設置響應文件類型,可以用下面這句話替換
response.setContentType(getServletContext().getMimeType(fileName) + ";charset=UTF-8");
看完上述內容,你們掌握利用servlet怎么實現一個文件上傳下載功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。