Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件上傳(一)
文件上傳和下載功能是Java Web必備技能,很實(shí)用。
本文使用的是Apache下的著名的文件上傳組件
org.apache.commons.fileupload 實(shí)現(xiàn)
下面結(jié)合最近看到的一些資料以及自己的嘗試,先寫第一篇文件上傳。后續(xù)會(huì)逐步實(shí)現(xiàn)下載,展示文件列表,上傳信息持久化等。
廢話少說(shuō),直接上代碼
第一步,引用jar包,設(shè)置上傳目錄
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
上傳目錄:WEB-INF/tempFiles和WEB-INF/uploadFiles
第二步,編寫JSP頁(yè)面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>文件上傳測(cè)試</title> </head> <body> <form method="POST" enctype="multipart/form-data" action="<%=request.getContextPath()%>/UploadServlet"> 文件: <input type="file" name="upfile"><br/> <br/> <input type="submit" value="上傳"> </form> <c:if test="${not empty errorMessage}"> <input type="text" id="errorMessage" value="${errorMessage}" style="color:red;" disabled="disabled"> </c:if> </body> </html>
第三步,編寫Servlet,處理文件上傳的核心
package servlet; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Iterator; import java.util.List; import java.util.UUID; /** * 處理文件上傳 * * @author xusucheng * @create 2017-12-27 **/ @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設(shè)置文件上傳基本路徑 String savePath = this.getServletContext().getRealPath("/WEB-INF/uploadFiles"); //設(shè)置臨時(shí)文件路徑 String tempPath = this.getServletContext().getRealPath("/WEB-INF/tempFiles"); File tempFile = new File(tempPath); if (!tempFile.exists()) { tempFile.mkdir(); } //定義異常消息 String errorMessage = ""; //創(chuàng)建file items工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //設(shè)置緩沖區(qū)大小 factory.setSizeThreshold(1024 * 100); //設(shè)置臨時(shí)文件路徑 factory.setRepository(tempFile); //創(chuàng)建文件上傳處理器 ServletFileUpload upload = new ServletFileUpload(factory); //監(jiān)聽文件上傳進(jìn)度 ProgressListener progressListener = new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("正在讀取文件: " + pItems); if (pContentLength == -1) { System.out.println("已讀?。?" + pBytesRead + " 剩余0"); } else { System.out.println("文件總大小:" + pContentLength + " 已讀?。? + pBytesRead); } } }; upload.setProgressListener(progressListener); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if (!ServletFileUpload.isMultipartContent(request)) { //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //設(shè)置上傳單個(gè)文件的大小的最大值,目前是設(shè)置為1024*1024字節(jié),也就是1MB upload.setFileSizeMax(1024 * 1024); //設(shè)置上傳文件總量的最大值,最大值=同時(shí)上傳的多個(gè)文件的大小的最大值的和,目前設(shè)置為10MB upload.setSizeMax(1024 * 1024 * 10); try { //使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = iterator.next(); //判斷jsp提交過(guò)來(lái)的是不是文件 if (item.isFormField()) { errorMessage = "請(qǐng)?zhí)峤晃募?; break; } else { //文件名 String fileName = item.getName(); if (fileName == null || fileName.trim() == "") { System.out.println("文件名為空!"); } //處理不同瀏覽器提交的文件名帶路徑問(wèn)題 fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); //文件擴(kuò)展名 String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1); //判斷擴(kuò)展名是否合法 if (!validExtension(fileExtension)) { errorMessage = "上傳文件非法!"; item.delete(); break; } //獲得文件輸入流 InputStream in = item.getInputStream(); //得到保存文件的名稱 String saveFileName = createFileName(fileName); //得到文件保存路徑 String realFilePath = createRealFilePath(savePath, saveFileName); //創(chuàng)建文件輸出流 FileOutputStream out = new FileOutputStream(realFilePath); //創(chuàng)建緩沖區(qū) byte buffer[] = new byte[1024]; int len = 0; while ((len = in.read(buffer)) > 0) { //寫文件 out.write(buffer, 0, len); } //關(guān)閉輸入流 in.close(); //關(guān)閉輸出流 out.close(); //刪除臨時(shí)文件 TODO item.delete(); //將上傳文件信息保存到附件表中 TODO } } } catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("errorMessage", "單個(gè)文件超出最大值?。。?); request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response); return; } catch (FileUploadBase.SizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("errorMessage", "上傳文件的總的大小超出限制的最大值?。?!"); request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response); return; } catch (FileUploadException e) { e.printStackTrace(); request.setAttribute("errorMessage", "文件上傳失?。。?!"); request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response); return; } request.setAttribute("errorMessage", errorMessage); request.getRequestDispatcher("pages/upload/upload.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } private boolean validExtension(String fileExtension) { String[] exts = {"jpg", "txt", "doc", "pdf"}; for (int i = 0; i < exts.length; i++) { if (fileExtension.equals(exts[i])) { return true; } } return false; } private String createFileName(String fileName) { return UUID.randomUUID().toString() + "_" + fileName; } /** * 根據(jù)基本路徑和文件名稱生成真實(shí)文件路徑,基本路徑\\年\\月\\fileName * * @param basePath * @param fileName * @return */ private String createRealFilePath(String basePath, String fileName) { Calendar today = Calendar.getInstance(); String year = String.valueOf(today.get(Calendar.YEAR)); String month = String.valueOf(today.get(Calendar.MONTH) + 1); String upPath = basePath + File.separator + year + File.separator + month + File.separator; File uploadFolder = new File(upPath); if (!uploadFolder.exists()) { uploadFolder.mkdirs(); } String realFilePath = upPath + fileName; return realFilePath; } }
第四步,測(cè)試
http://localhost:8080/helloweb/pages/upload/upload.jsp
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。
上一篇:tomcat共享多個(gè)web應(yīng)用會(huì)話的實(shí)現(xiàn)方法
欄 目:JSP編程
下一篇:秒殺系統(tǒng)Web層設(shè)計(jì)的實(shí)現(xiàn)方法
本文標(biāo)題:Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件上傳(一)
本文地址:http://mengdiqiu.com.cn/a1/JSPbiancheng/11436.html
您可能感興趣的文章
- 01-11web下載文件和跳轉(zhuǎn)的方法
- 01-11jsp文件下載功能實(shí)現(xiàn)代碼
- 01-11Spring獲取ApplicationContext對(duì)象工具類的實(shí)現(xiàn)方法
- 01-11web前端超出兩行用省略號(hào)表示的實(shí)現(xiàn)方法
- 01-11JSP servlet實(shí)現(xiàn)文件上傳下載和刪除
- 01-11jsp+servlet實(shí)現(xiàn)文件上傳與下載功能
- 01-11將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法
- 01-11秒殺系統(tǒng)Web層設(shè)計(jì)的實(shí)現(xiàn)方法
- 01-11tomcat共享多個(gè)web應(yīng)用會(huì)話的實(shí)現(xiàn)方法
- 01-11Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問(wèn)題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-11web下載文件和跳轉(zhuǎn)的方法
- 01-11Spring注入Date類型的三種方法總結(jié)
- 01-11在JSP中使用formatNumber控制要顯示的小
- 01-11Properties 持久的屬性集的實(shí)例詳解
- 01-11EJB3.0部署消息驅(qū)動(dòng)Bean拋javax.naming.Na
- 01-11jsp文件下載功能實(shí)現(xiàn)代碼
- 01-11JSP頁(yè)面跳轉(zhuǎn)方法大全
- 01-11詳解Spring的核心機(jī)制依賴注入
- 01-11jsp 使用request為頁(yè)面添加靜態(tài)數(shù)據(jù)的實(shí)
- 01-11Spring獲取ApplicationContext對(duì)象工具類的
隨機(jī)閱讀
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 04-02jquery與jsp,用jquery
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-10delphi制作wav文件的方法
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?