利用servlet怎么實(shí)現(xiàn)一個(gè)文件上傳下載功能?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
創(chuàng)新互聯(lián)建站主要從事成都網(wǎng)站制作、成都做網(wǎng)站、網(wǎng)頁(yè)設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)水城,十載網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來(lái)電咨詢建站服務(wù):13518219792
一、準(zhǔn)備工作:
1.1 文件上傳插件:uploadify;
1.2 文件上傳所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar
1.3 將數(shù)據(jù)轉(zhuǎn)成JSON對(duì)象需要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 開(kāi)發(fā)工具:我用的是Eclipse,隨意
1.5 目錄結(jié)構(gòu)
需要注意的是:變更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 客戶端代碼設(shè)計(jì)
JSP部分
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>演示-操作文件 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> "> "> " type="text/css" rel="stylesheet"/> ">
序號(hào) | 文件名 | 文件預(yù)覽 | 文件下載 | 文件刪除 |
---|
js文件
var operateFile = new OperateFile(); window.onload = function() { operateFile.init(); } /** * 對(duì)文件進(jìn)行操作 * @returns */ function OperateFile() { var object = this; /** * 初始化操作: */ this.init = function() { // 隊(duì)列中的文件數(shù) var selectedCount = 0; $('#file_upload').uploadify({ 'method' : 'get',// 默認(rèn)值post,設(shè)置成get是為了向后臺(tái)傳遞自定義的參數(shù) 'auto' : false,// 設(shè)置為true當(dāng)選擇文件后就直接上傳了,為false需要點(diǎn)擊上傳按鈕才上傳。默認(rèn)值為T(mén)RUE 'buttonText' : '添加文件',// 按鈕文本 'fileTypeExts' : '*.gif; *.jpg; *.png;*.pdf;*.zip;',// 限制上傳文件類型,默認(rèn)值沒(méi)有限制(*.*) 'fileTypeDesc' : '請(qǐng)選擇gif jpg png pdf zip類型的文件',// 這個(gè)屬性值必須設(shè)置fileTypeExts屬性后才有效,用來(lái)設(shè)置選擇文件對(duì)話框中的提示文本,默認(rèn)值:All Files 'swf' : baseUrl + '/uploadify/flash/uploadify.swf', // flash文件路徑(幫助我們與后端交互數(shù)據(jù)) 'uploader' : baseUrl + '/uploadFile.do' , // 處理文件上傳請(qǐng)求地址 'formData' : {'param1':'測(cè)試文件上傳'},// 請(qǐng)求參數(shù):上傳每個(gè)文件的同時(shí)提交到服務(wù)器的額外數(shù)據(jù) 'onDialogClose' : function(queueData) { // 獲取該隊(duì)列中有多少個(gè)要上傳的文件 var queueSize = $('#file_upload-queue').children('div').length; if (queueSize > 0) { $('#ctrlUpload').show(); } }, 'onUploadSuccess' : function(file, data, response) {// 上傳成功 // 將josn字符串轉(zhuǎn)換成JSON對(duì)象 data = eval('(' + data + ')'); // 獲取頁(yè)面上文件展示table 有多少行 var rowsLength = $('#tableFiles')[0].rows.length; // 設(shè)置查看文件所需參數(shù) var param = "fileName=" + data.fileName; // 查看文件請(qǐng)求地址 var viewUrl = baseUrl + '/viewFile.do?' + param; // 下載文件請(qǐng)求地址 var downloadUrl = baseUrl + '/downloadFile.do?' + param; // 拼接一行tr var trTemplate = '' + ' '; $('#tableFiles').append(trTemplate); }, 'onUploadError' : function(file, errorCode, errorMsg, errorString) {// 上傳失敗 } }); } /** * 刪除文件 * @param 文件名 */ this.deleteFile = function(fileName,rowIndex) { // 設(shè)置刪除文件所需參數(shù) var param = "fileName=" + fileName; // 刪除文件請(qǐng)求地址 var deleteUrl = baseUrl + '/deleteFile.do?' + param; $.get( deleteUrl, function(msg) { alert(msg); if ("刪除失敗!" != msg) { // 刪除該行記錄 $('#tableFiles')[0].deleteRow(rowIndex); } } ); } }' + rowsLength + ' ' + '' + file.name // 仍展示原文件名 + ' ' + '' + '點(diǎn)擊預(yù)覽' + '' + ' ' + '' + '點(diǎn)擊下載' + ' ' + '' + '點(diǎn)擊刪除' + ' ' +'
2.2 服務(wù)器端代碼設(shè)計(jì)
文件上傳代碼(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.設(shè)置參數(shù)編碼 request.setCharacterEncoding("UTF-8"); // 設(shè)置響應(yīng)數(shù)據(jù)字符集 response.setCharacterEncoding("UTF-8"); // 設(shè)置響應(yīng)數(shù)據(jù)格式 // response.setContentType("application/json; charset=UTF-8"); PrintWriter out = response.getWriter(); // 2.創(chuàng)建文件上傳處理工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 3.設(shè)置臨時(shí)文件存放地點(diǎn) // 3.1獲取當(dāng)前web應(yīng)用程序?qū)ο螅╓EB容器在啟動(dòng)時(shí),它會(huì)為每個(gè)WEB應(yīng)用程序都創(chuàng)建一個(gè)對(duì)應(yīng)的ServletContext對(duì)象,它代表當(dāng)前web應(yīng)用) ServletContext servletContext = this.getServletConfig().getServletContext(); // 3.2獲取服務(wù)器的臨時(shí)目錄(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臨時(shí)文件將會(huì)存儲(chǔ)在該目錄下 factory.setRepository(repository); // 4.創(chuàng)建文件上傳處理器 ServletFileUpload upload = new ServletFileUpload(factory); // 5.判斷請(qǐng)求類型是否為文件上傳類型 boolean multipartContent = upload.isMultipartContent(request); MapmapData = new HashMap (); // 返回信息 String msg = ""; // 錯(cuò)誤信息 String errorMsg = ""; // 文件名 String fileName = ""; if (multipartContent) { try { // 獲取請(qǐng)求參數(shù) String param = request.getParameter("param1"); System.out.println(param); // 6.解析請(qǐng)求信息 List items = upload.parseRequest(request); // 7.對(duì)所有請(qǐng)求信息進(jìn)行判斷 Iterator 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,無(wú)法上傳!"; } mapData.put("msg", msg); mapData.put("errorMsg", errorMsg); mapData.put("fileName", fileName); // 將Map轉(zhuǎn)成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();// 默認(rèn)值為Filedata // 獲取文件名 String fileName = item.getName(); // 內(nèi)容類型: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.路徑構(gòu)成:/uploadfile/fileName // TODO 可以自定義文件存放路徑 // 3.根據(jù)路徑批量創(chuàng)建文件夾 File fileDirectories = new File(path); // 目錄不存在時(shí),再創(chuàng)建 if (!fileDirectories.exists()) { fileDirectories.mkdirs();// 所有的文件夾都創(chuàng)建成功才返回TRUE } // 4.文件名格式校驗(yàn)(文件名中不能包含#號(hào)) int index = fileName.indexOf("#"); if (index > -1) { fileName = fileName.replace('#', '_'); } // TODO 可以對(duì)文件名進(jìn)行重命名 // 5.在指定路徑下創(chuàng)建指定名稱的文件 File uploadedFile = new File(path + "/" + fileName); // 6.判斷該文件是否已存在 if (!uploadedFile.exists()) { try { // 使用了這個(gè)方法寫(xiě)入文件,臨時(shí)文件會(huì)被系統(tǒng)自動(dòng)刪除 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; // 設(shè)定輸出的類型 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.設(shè)置參數(shù)編碼 request.setCharacterEncoding("UTF-8"); // 2.設(shè)置響應(yīng)數(shù)據(jù)字符集 response.setCharacterEncoding("UTF-8"); // 3.獲取客戶端請(qǐng)求參數(shù):文件名 String fileName = request.getParameter("fileName"); // 4.重置response response.reset(); // 5.設(shè)置響應(yīng)數(shù)據(jù)格式 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; // 獲取當(dāng)前web應(yīng)用程序 ServletContext webApp = this.getServletContext(); // 6.獲取指定文件上傳的真實(shí)路徑 filePath = webApp.getRealPath(filePath); // 7.讀取目標(biāo)文件,通過(guò)response將目標(biāo)文件寫(xiě)到客戶端 is = new FileInputStream(filePath); bis = new BufferedInputStream(is); output = response.getOutputStream(); bos = new BufferedOutputStream(output); byte data[] = new byte[1024];// 緩沖字節(jié)數(shù) int size = bis.read(data); while (size != -1) { bos.write(data, 0, size); size = bis.read(data); } // 關(guān)閉流 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.設(shè)置參數(shù)編碼 request.setCharacterEncoding("UTF-8"); // 設(shè)置響應(yīng)數(shù)據(jù)字符集 response.setCharacterEncoding("UTF-8"); // 1.獲得請(qǐng)求文件名 String fileName = request.getParameter("fileName"); // 2.設(shè)置文件MIME類型(指定要返回內(nèi)容的類型) response.setContentType(getServletContext().getMimeType(fileName)); // 3.設(shè)置Content-Disposition(指定下載該文件時(shí)的文件名) response.setHeader("content-disposition", "attachment;filename=" + fileName); // 4.讀取目標(biāo)文件,通過(guò)response將目標(biāo)文件寫(xiě)到客戶端 // 4.1 獲取目標(biāo)文件的絕對(duì)路徑 String filePath = "WEB-INF/uploadFiles/" + fileName; filePath = this.getServletContext().getRealPath(filePath); // 4.2 讀取文件 InputStream in = new FileInputStream(filePath); // 4.3 輸出文件 OutputStream out = response.getOutputStream(); // 寫(xiě)文件 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.設(shè)置參數(shù)編碼 request.setCharacterEncoding("UTF-8"); // 設(shè)置響應(yīng)數(shù)據(jù)字符集 response.setCharacterEncoding("UTF-8"); // 2.獲得請(qǐng)求文件名 String fileName = request.getParameter("fileName"); // 3.獲取該文件所在路徑 String filePath = "WEB-INF/uploadFiles/" + fileName; filePath = this.getServletContext().getRealPath(filePath); // 4.在指定路徑下創(chuàng)建指定名稱的文件 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"?>demo_uploadAndDownload webAppRootKey uploadAndDownload upload controller.fileHandler.FileUpload upload /uploadFile.do view controller.fileHandler.FileView view /viewFile.do download controller.fileHandler.FileDownload download /downloadFile.do delete controller.fileHandler.FileDelete delete /deleteFile index.html index.htm index.jsp default.html default.htm default.jsp
2.3 代碼優(yōu)化
處理文件查看(FileView.java) ,設(shè)置響應(yīng)文件類型,可以用下面這句話替換
response.setContentType(getServletContext().getMimeType(fileName) + ";charset=UTF-8");
看完上述內(nèi)容,你們掌握利用servlet怎么實(shí)現(xiàn)一個(gè)文件上傳下載功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!