JavaWeb中上傳和下載文件實(shí)例代碼
一丶先引入上傳下載的lib
二丶上傳的的servlet
package com.test.action; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; 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 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; @WebServlet("/upload") public class FileUpLoadAction extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 設(shè)置編碼 request.setCharacterEncoding("utf-8"); //對(duì)提交的數(shù)據(jù)進(jìn)行處理,保存上傳文件 boolean success = processUpload(request); if(success){ //獲取表單text控件的值 String account = request.getAttribute("account").toString(); System.out.println(account); //獲取文件上傳的原始名稱 String fileName = request.getAttribute("upfile").toString(); System.out.println(fileName); //獲取文件上傳后,服務(wù)器上保存的名字 String fileNameServer = request.getAttribute("upfileServer").toString(); System.out.println(fileNameServer); request.setAttribute("upfile", fileNameServer); request.setAttribute("message", "上傳成功"); } request.getRequestDispatcher("/upload.jsp").forward(request, response); } private boolean processUpload(HttpServletRequest request) { boolean success = true; String message = null; // 獲取文件需要上傳到的路徑 String path = request.getServletContext().getRealPath("/upload"); System.out.println(path); // 如果此文件夾不存在,則構(gòu)造此文件夾 File f = new File(path); if (!f.exists()) { f.mkdir(); } // 構(gòu)造出文件工廠,用于存放JSP頁(yè)面中傳遞過(guò)來(lái)的文件 DiskFileItemFactory factory = new DiskFileItemFactory(); // 設(shè)置上傳文件的保存路徑 factory.setRepository(f); // 設(shè)置緩存大小,如果文件大于緩存大小時(shí),則先把文件放到緩存中 factory.setSizeThreshold(1 * 1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); // 設(shè)置可以上傳文件大小的上界20MB upload.setSizeMax(20 * 1024 * 1024); try { // 可以上傳多個(gè)文件 List<FileItem> list = (List<FileItem>) upload.parseRequest(request); for (FileItem item : list) { // 獲取表單的屬性名字 String name = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); //解決亂碼問(wèn)題 value = new String(value.getBytes("iso-8859-1"),"utf-8"); request.setAttribute(name, value); } else { // 獲得文件類型 String contentType = item.getContentType(); // 獲得文件大小 long fileSize = item.getSize(); // 獲取路徑名 String value = item.getName(); // 索引到最后一個(gè)反斜杠 int start = value.lastIndexOf("\\"); // 截取 上傳文件的 字符串名字,加1是 去掉反斜杠, String filename = value.substring(start + 1); if (filename != null && !filename.trim().equals("")) { // 如果上傳的文件不是圖片,那么不上傳 String allImgExt = ".jpg|.jpeg|.gif|.bmp|.png|"; String extName = filename.substring(filename.indexOf("."), filename.length()); if (allImgExt.indexOf(extName + "|") == -1) { message = "該文件類型不允許上傳。請(qǐng)上傳 " + allImgExt + " 類型的文件,當(dāng)前文件類型為" + extName; success = false; break; } request.setAttribute(name, filename); // 隨機(jī)數(shù)產(chǎn)生名稱 String newName = System.currentTimeMillis() + extName; request.setAttribute(name + "Server", newName); // 將文件保存到服務(wù)器中 InputStream in = item.getInputStream(); // 原文件名 // OutputStream out = new FileOutputStream(new File(path, filename)); // 隨機(jī)數(shù)文件名 OutputStream out = new FileOutputStream(new File(path, newName)); int length = 0; byte[] buf = new byte[1024]; while ((length = in.read(buf)) != -1) { out.write(buf, 0, length); } in.close(); out.close(); } } } } catch (FileUploadException e) { message = "文件的內(nèi)容過(guò)大,請(qǐng)上傳小于20MB的文件" ; success = false; e.printStackTrace(); } catch (IOException e) { success = false; e.printStackTrace(); } request.setAttribute("message", message); return success; } }
三丶下載的servlet
package com.test.action; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/download") public class FileDownloadAction extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); // 根據(jù)主鍵讀取文件的真實(shí)名字 + 服務(wù)器上的名字 processDownload("1444442288605.png", "騰訊.png", request, response); } private boolean processDownload(String fileName, String saveName, HttpServletRequest request, HttpServletResponse response) { boolean success = true; // 獲取文件下載所在的路徑 String path = request.getServletContext().getRealPath("/upload"); File fileLoad = new File(path, fileName); // 下載文件 long fileLength = fileLoad.length(); // 文件大小 byte[] buffer = new byte[1024]; // 緩沖字節(jié)數(shù)組 try { response.reset(); response.setHeader("Content-disposition", "attachment;filename=\"" + new String(saveName.getBytes("gb2312"), "ISO-8859-1") + "\""); response.setContentType("application/octet-stream"); response.setHeader("Content_Length", String.valueOf(fileLength)); OutputStream os = response.getOutputStream(); FileInputStream in = new FileInputStream(fileLoad); int hasRead = 0; while ((hasRead = in.read(buffer)) != -1) { os.write(buffer, 0, hasRead); } os.flush(); os.close(); in.close(); } catch (IOException e) { success = false; e.printStackTrace(); } return success; } }
以上所述是小編給大家介紹的JavaWeb中上傳和下載文件實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
使用Java實(shí)現(xiàn)創(chuàng)建Excel表單控件
在數(shù)據(jù)填報(bào)時(shí),創(chuàng)建Excel表單控件是一項(xiàng)常見(jiàn)的任務(wù),它可以極大地簡(jiǎn)化數(shù)據(jù)收集和處理的過(guò)程,本文主要介紹了如何使用Java實(shí)現(xiàn)創(chuàng)建Excel表單控件,感興趣的可以了解下2024-03-03Java結(jié)構(gòu)性設(shè)計(jì)模式中的裝飾器模式介紹使用
裝飾器模式又名包裝(Wrapper)模式。裝飾器模式以對(duì)客戶端透明的方式拓展對(duì)象的功能,是繼承關(guān)系的一種替代方案,本篇文章以虹貓藍(lán)兔生動(dòng)形象的為你帶來(lái)詳細(xì)講解2022-09-09教你如何用Jenkins自動(dòng)化部署項(xiàng)目(從零到搭建完成)
這篇文章主要介紹了教你如何用Jenkins自動(dòng)化部署項(xiàng)目(從零到搭建完成),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Java中 URL實(shí)現(xiàn)斷點(diǎn)下載
Java中 URL實(shí)現(xiàn)斷點(diǎn)下載,需要的朋友可以參考一下2013-03-03Spring自動(dòng)掃描無(wú)法掃描jar包中bean的解決方法
在日常開(kāi)發(fā)中往往會(huì)對(duì)公共的模塊打包發(fā)布,然后調(diào)用公共包的內(nèi)容。然而,最近對(duì)公司的公共模塊進(jìn)行整理發(fā)布后。spring卻無(wú)法掃描到相應(yīng)的bean,下面這篇文章主要給大家介紹了關(guān)于Spring自動(dòng)掃描時(shí)無(wú)法掃描jar包中bean的解決方法,需要的朋友可以參考下。2017-06-06Java PDF 添加數(shù)字簽名的實(shí)現(xiàn)方法
這篇文章主要介紹了Java PDF 添加數(shù)字簽名的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12