Java文件上傳下載、郵件收發(fā)實(shí)例代碼
文件上傳下載
前臺:
1. 提交方式:post
2. 表單中有文件上傳的表單項(xiàng): <input type=”file” />
3. 指定表單類型:
默認(rèn)類型:enctype="application/x-www-form-urlencoded"
文件上傳類型:multipart/form-data
FileUpload
文件上傳功能開發(fā)中比較常用,apache也提供了文件上傳組件!
FileUpload組件:
1. 下載源碼
2. 項(xiàng)目中引入jar文件
commons-fileupload-1.2.1.jar 【文件上傳組件核心jar包】
commons-io-1.4.jar 【封裝了對文件處理的相關(guān)工具類】
使用:
public class UploadServlet extends HttpServlet { // upload目錄,保存上傳的資源 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*********文件上傳組件: 處理文件上傳************/ try { // 1. 文件上傳工廠 FileItemFactory factory = new DiskFileItemFactory(); // 2. 創(chuàng)建文件上傳核心工具類 ServletFileUpload upload = new ServletFileUpload(factory); // 一、設(shè)置單個(gè)文件允許的最大的大小: 30M upload.setFileSizeMax(30*1024*1024); // 二、設(shè)置文件上傳表單允許的總大小: 80M upload.setSizeMax(80*1024*1024); // 三、 設(shè)置上傳表單文件名的編碼 // 相當(dāng)于:request.setCharacterEncoding("UTF-8"); upload.setHeaderEncoding("UTF-8"); // 3. 判斷: 當(dāng)前表單是否為文件上傳表單 if (upload.isMultipartContent(request)){ // 4. 把請求數(shù)據(jù)轉(zhuǎn)換為一個(gè)個(gè)FileItem對象,再用集合封裝 List<FileItem> list = upload.parseRequest(request); // 遍歷: 得到每一個(gè)上傳的數(shù)據(jù) for (FileItem item: list){ // 判斷:普通文本數(shù)據(jù) if (item.isFormField()){ // 普通文本數(shù)據(jù) String fieldName = item.getFieldName(); // 表單元素名稱 String content = item.getString(); // 表單元素名稱, 對應(yīng)的數(shù)據(jù) //item.getString("UTF-8"); 指定編碼 System.out.println(fieldName + " " + content); } // 上傳文件(文件流) ----> 上傳到upload目錄下 else { // 普通文本數(shù)據(jù) String fieldName = item.getFieldName(); // 表單元素名稱 String name = item.getName(); // 文件名 String content = item.getString(); // 表單元素名稱, 對應(yīng)的數(shù)據(jù) String type = item.getContentType(); // 文件類型 InputStream in = item.getInputStream(); // 上傳文件流 /* * 四、文件名重名 * 對于不同用戶readme.txt文件,不希望覆蓋! * 后臺處理: 給用戶添加一個(gè)唯一標(biāo)記! */ // a. 隨機(jī)生成一個(gè)唯一標(biāo)記 String id = UUID.randomUUID().toString(); // b. 與文件名拼接 name = id +"#"+ name; // 獲取上傳基路徑 String path = getServletContext().getRealPath("/upload"); // 創(chuàng)建目標(biāo)文件 File file = new File(path,name); // 工具類,文件上傳 item.write(file); item.delete(); //刪除系統(tǒng)產(chǎn)生的臨時(shí)文件 System.out.println(); } } } else { System.out.println("當(dāng)前表單不是文件上傳表單,處理失??!"); } } catch (Exception e) { e.printStackTrace(); } } // 手動(dòng)實(shí)現(xiàn)過程 private void upload(HttpServletRequest request) throws IOException, UnsupportedEncodingException { /* request.getParameter(""); // GET/POST request.getQueryString(); // 獲取GET提交的數(shù)據(jù) request.getInputStream(); // 獲取post提交的數(shù)據(jù) */ /***********手動(dòng)獲取文件上傳表單數(shù)據(jù)************/ //1. 獲取表單數(shù)據(jù)流 InputStream in = request.getInputStream(); //2. 轉(zhuǎn)換流 InputStreamReader inStream = new InputStreamReader(in, "UTF-8"); //3. 緩沖流 BufferedReader reader = new BufferedReader(inStream); // 輸出數(shù)據(jù) String str = null; while ((str = reader.readLine()) != null) { System.out.println(str); } // 關(guān)閉 reader.close(); inStream.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
案例:
Index.jsp
<body> <a href="${pageContext.request.contextPath }/upload.jsp">文件上傳</a> <a href="${pageContext.request.contextPath }/fileServlet?method=downList">文件下載</a> </body>
Upload.jsp
<body> <form name="frm_test" action="${pageContext.request.contextPath }/fileServlet?method=upload" method="post" enctype="multipart/form-data"> <%--<input type="hidden" name="method" value="upload">--%> 用戶名:<input type="text" name="userName"> <br/> 文件: <input type="file" name="file_img"> <br/> <input type="submit" value="提交"> </form> </body>
FileServlet.Java
/** * 處理文件上傳與下載 * @author Jie.Yuan * */ public class FileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取請求參數(shù): 區(qū)分不同的操作類型 String method = request.getParameter("method"); if ("upload".equals(method)) { // 上傳 upload(request,response); } else if ("downList".equals(method)) { // 進(jìn)入下載列表 downList(request,response); } else if ("down".equals(method)) { // 下載 down(request,response); } } /** * 1. 上傳 */ private void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 1. 創(chuàng)建工廠對象 FileItemFactory factory = new DiskFileItemFactory(); // 2. 文件上傳核心工具類 ServletFileUpload upload = new ServletFileUpload(factory); // 設(shè)置大小限制參數(shù) upload.setFileSizeMax(10*1024*1024); // 單個(gè)文件大小限制 upload.setSizeMax(50*1024*1024); // 總文件大小限制 upload.setHeaderEncoding("UTF-8"); // 對中文文件編碼處理 // 判斷 if (upload.isMultipartContent(request)) { // 3. 把請求數(shù)據(jù)轉(zhuǎn)換為list集合 List<FileItem> list = upload.parseRequest(request); // 遍歷 for (FileItem item : list){ // 判斷:普通文本數(shù)據(jù) if (item.isFormField()){ // 獲取名稱 String name = item.getFieldName(); // 獲取值 String value = item.getString(); System.out.println(value); } // 文件表單項(xiàng) else { /******** 文件上傳 ***********/ // a. 獲取文件名稱 String name = item.getName(); // ----處理上傳文件名重名問題---- // a1. 先得到唯一標(biāo)記 String id = UUID.randomUUID().toString(); // a2. 拼接文件名 name = id + "#" + name; // b. 得到上傳目錄 String basePath = getServletContext().getRealPath("/upload"); // c. 創(chuàng)建要上傳的文件對象 File file = new File(basePath,name); // d. 上傳 item.write(file); item.delete(); // 刪除組件運(yùn)行時(shí)產(chǎn)生的臨時(shí)文件 } } } } catch (Exception e) { e.printStackTrace(); } } /** * 2. 進(jìn)入下載列表 */ private void downList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 實(shí)現(xiàn)思路:先獲取upload目錄下所有文件的文件名,再保存;跳轉(zhuǎn)到down.jsp列表展示 //1. 初始化map集合Map<包含唯一標(biāo)記的文件名, 簡短文件名> ; Map<String,String> fileNames = new HashMap<String,String>(); //2. 獲取上傳目錄,及其下所有的文件的文件名 String bathPath = getServletContext().getRealPath("/upload"); // 目錄 File file = new File(bathPath); // 目錄下,所有文件名 String list[] = file.list(); // 遍歷,封裝 if (list != null && list.length > 0){ for (int i=0; i<list.length; i++){ // 全名 String fileName = list[i]; // 短名 String shortName = fileName.substring(fileName.lastIndexOf("#")+1); // 封裝 fileNames.put(fileName, shortName); } } // 3. 保存到request域 request.setAttribute("fileNames", fileNames); // 4. 轉(zhuǎn)發(fā) request.getRequestDispatcher("/downlist.jsp").forward(request, response); } /** * 3. 處理下載 */ private void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取用戶下載的文件名稱(url地址后追加數(shù)據(jù),get) String fileName = request.getParameter("fileName"); fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8"); // 先獲取上傳目錄路徑 String basePath = getServletContext().getRealPath("/upload"); // 獲取一個(gè)文件流 InputStream in = new FileInputStream(new File(basePath,fileName)); // 如果文件名是中文,需要進(jìn)行url編碼 fileName = URLEncoder.encode(fileName, "UTF-8"); // 設(shè)置下載的響應(yīng)頭 response.setHeader("content-disposition", "attachment;fileName=" + fileName); // 獲取response字節(jié)流 OutputStream out = response.getOutputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = in.read(b)) != -1){ out.write(b, 0, len); } // 關(guān)閉 out.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
郵件開發(fā)
準(zhǔn)備工作, 環(huán)境搭建:
1. 本地搭建一個(gè)郵件服務(wù)器
易郵服務(wù)器,eyoumailserversetup.exe
2. 新建郵箱賬號
張三給李四發(fā)郵件。
步驟1:
新建域名: 工具, 服務(wù)器設(shè)置, 單域名框中輸入 itcast.com
步驟2:
新建郵箱賬號: zhangsan@itcast.com
3. 安裝foxmail
配置郵件發(fā)送服務(wù)器(smtp): localhost 25
郵件接收服務(wù)器(pop3): localhost 110
再新建賬號,就可以接收郵件了!
注意
注意
如果是web項(xiàng)目,因?yàn)閖avaee自帶的有郵件功能,可能存在問題!
我們要用自己的mail.jar文件功能! 需要?jiǎng)h除javaee中mail包!
使用:
JavaMail開發(fā),先引入jar文件:
activation.jar 【如果使用jdk1.6或以上版本,可以不用這個(gè)jar文件】 mail.jar 【郵件發(fā)送核心包】 /** * 1. 發(fā)送一封普通郵件 * @author Jie.Yuan * */ public class App_SendMail { @Test public void testSend() throws Exception { //0. 郵件參數(shù) Properties prop = new Properties(); prop.put("mail.transport.protocol", "smtp"); // 指定協(xié)議 prop.put("mail.smtp.host", "localhost"); // 主機(jī) stmp.qq.com prop.put("mail.smtp.port", 25); // 端口 prop.put("mail.smtp.auth", "true"); // 用戶密碼認(rèn)證 prop.put("mail.debug", "true"); // 調(diào)試模式 //1. 創(chuàng)建一個(gè)郵件的會(huì)話 Session session = Session.getDefaultInstance(prop); //2. 創(chuàng)建郵件體對象 (整封郵件對象) MimeMessage message = new MimeMessage(session); //3. 設(shè)置郵件體參數(shù): //3.1 標(biāo)題 message.setSubject("我的第一封郵件 "); //3.2 郵件發(fā)送時(shí)間 message.setSentDate(new Date()); //3.3 發(fā)件人 message.setSender(new InternetAddress("zhangsan@itcast.com")); //3.4 接收人 message.setRecipient(RecipientType.TO, new InternetAddress("lisi@itcast.com")); //3.5內(nèi)容 message.setText("你好,已經(jīng)發(fā)送成功! 正文...."); // 簡單純文本郵件 message.saveChanges(); // 保存郵件(可選) //4. 發(fā)送 Transport trans = session.getTransport(); trans.connect("zhangsan", "888"); // 發(fā)送郵件 trans.sendMessage(message, message.getAllRecipients()); trans.close(); } }
帶圖片
/** * 帶圖片資源的郵件 * @author Jie.Yuan * */ public class App_2SendWithImg { // 初始化參數(shù) private static Properties prop; // 發(fā)件人 private static InternetAddress sendMan = null; static { prop = new Properties(); prop.put("mail.transport.protocol", "smtp"); // 指定協(xié)議 prop.put("mail.smtp.host", "localhost"); // 主機(jī) stmp.qq.com prop.put("mail.smtp.port", 25); // 端口 prop.put("mail.smtp.auth", "true"); // 用戶密碼認(rèn)證 prop.put("mail.debug", "true"); // 調(diào)試模式 try { sendMan = new InternetAddress("zhangsan@itcast.com"); } catch (AddressException e) { throw new RuntimeException(e); } } @Test public void testSend() throws Exception { // 1. 創(chuàng)建郵件會(huì)話 Session session = Session.getDefaultInstance(prop); // 2. 創(chuàng)建郵件對象 MimeMessage message = new MimeMessage(session); // 3. 設(shè)置參數(shù):標(biāo)題、發(fā)件人、收件人、發(fā)送時(shí)間、內(nèi)容 message.setSubject("帶圖片郵件"); message.setSender(sendMan); message.setRecipient(RecipientType.TO, new InternetAddress("lisi@itcast.com")); message.setSentDate(new Date()); /***************設(shè)置郵件內(nèi)容: 多功能用戶郵件 (related)*******************/ // 4.1 構(gòu)建一個(gè)多功能郵件塊 MimeMultipart related = new MimeMultipart("related"); // 4.2 構(gòu)建多功能郵件塊內(nèi)容 = 左側(cè)文本 + 右側(cè)圖片資源 MimeBodyPart content = new MimeBodyPart(); MimeBodyPart resource = new MimeBodyPart(); // 設(shè)置具體內(nèi)容: a.資源(圖片) String filePath = App_2SendWithImg.class.getResource("8.jpg").getPath(); DataSource ds = new FileDataSource(new File(filePath)); DataHandler handler = new DataHandler(ds); resource.setDataHandler(handler); resource.setContentID("8.jpg"); // 設(shè)置資源名稱,給外鍵引用 // 設(shè)置具體內(nèi)容: b.文本 content.setContent("<img src='cid:8.jpg'/> 好哈哈!", "text/html;charset=UTF-8"); related.addBodyPart(content); related.addBodyPart(resource); /*******4.3 把構(gòu)建的復(fù)雜郵件快,添加到郵件中********/ message.setContent(related); // 5. 發(fā)送 Transport trans = session.getTransport(); trans.connect("zhangsan", "888"); trans.sendMessage(message, message.getAllRecipients()); trans.close(); } }
圖片+附件
/** * 3. 帶圖片資源以及附件的郵件 * @author Jie.Yuan * */ public class App_3ImgAndAtta { // 初始化參數(shù) private static Properties prop; // 發(fā)件人 private static InternetAddress sendMan = null; static { prop = new Properties(); prop.put("mail.transport.protocol", "smtp"); // 指定協(xié)議 prop.put("mail.smtp.host", "localhost"); // 主機(jī) stmp.qq.com prop.put("mail.smtp.port", 25); // 端口 prop.put("mail.smtp.auth", "true"); // 用戶密碼認(rèn)證 prop.put("mail.debug", "true"); // 調(diào)試模式 try { sendMan = new InternetAddress("zhangsan@itcast.com"); } catch (AddressException e) { throw new RuntimeException(e); } } @Test public void testSend() throws Exception { // 1. 創(chuàng)建郵件會(huì)話 Session session = Session.getDefaultInstance(prop); // 2. 創(chuàng)建郵件對象 MimeMessage message = new MimeMessage(session); // 3. 設(shè)置參數(shù):標(biāo)題、發(fā)件人、收件人、發(fā)送時(shí)間、內(nèi)容 message.setSubject("帶圖片郵件"); message.setSender(sendMan); message.setRecipient(RecipientType.TO, new InternetAddress("lisi@itcast.com")); message.setSentDate(new Date()); /* * 帶附件(圖片)郵件開發(fā) */ // 構(gòu)建一個(gè)總的郵件塊 MimeMultipart mixed = new MimeMultipart("mixed"); // ---> 總郵件快,設(shè)置到郵件對象中 message.setContent(mixed); // 左側(cè): (文本+圖片資源) MimeBodyPart left = new MimeBodyPart(); // 右側(cè): 附件 MimeBodyPart right = new MimeBodyPart(); // 設(shè)置到總郵件塊 mixed.addBodyPart(left); mixed.addBodyPart(right); /******附件********/ String attr_path = this.getClass().getResource("a.docx").getPath(); DataSource attr_ds = new FileDataSource(new File(attr_path)); DataHandler attr_handler = new DataHandler(attr_ds); right.setDataHandler(attr_handler); right.setFileName("a.docx"); /***************設(shè)置郵件內(nèi)容: 多功能用戶郵件 (related)*******************/ // 4.1 構(gòu)建一個(gè)多功能郵件塊 MimeMultipart related = new MimeMultipart("related"); // ----> 設(shè)置到總郵件快的左側(cè)中 left.setContent(related); // 4.2 構(gòu)建多功能郵件塊內(nèi)容 = 左側(cè)文本 + 右側(cè)圖片資源 MimeBodyPart content = new MimeBodyPart(); MimeBodyPart resource = new MimeBodyPart(); // 設(shè)置具體內(nèi)容: a.資源(圖片) String filePath = App_3ImgAndAtta.class.getResource("8.jpg").getPath(); DataSource ds = new FileDataSource(new File(filePath)); DataHandler handler = new DataHandler(ds); resource.setDataHandler(handler); resource.setContentID("8.jpg"); // 設(shè)置資源名稱,給外鍵引用 // 設(shè)置具體內(nèi)容: b.文本 content.setContent("<img src='cid:8.jpg'/> 好哈哈!", "text/html;charset=UTF-8"); related.addBodyPart(content); related.addBodyPart(resource); // 5. 發(fā)送 Transport trans = session.getTransport(); trans.connect("zhangsan", "888"); trans.sendMessage(message, message.getAllRecipients()); trans.close(); } }
以上所述是小編給大家介紹的Java文件上傳下載、郵件收發(fā)實(shí)例代碼 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
java基礎(chǔ)之接口組成更新的實(shí)現(xiàn)
本文主要介紹了java基礎(chǔ)之接口組成更新的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04CompletableFuture并行處理List分批數(shù)據(jù)demo
這篇文章主要介紹了CompletableFuture并行處理List分批數(shù)據(jù)實(shí)現(xiàn)實(shí)例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11java實(shí)現(xiàn)網(wǎng)上購物車程序
這篇文章主要介紹了java實(shí)現(xiàn)網(wǎng)上購物車程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Java虛擬機(jī)運(yùn)行時(shí)數(shù)據(jù)區(qū)域匯總
這篇文章主要給大家介紹了關(guān)于Java虛擬機(jī)運(yùn)行時(shí)數(shù)據(jù)區(qū)域的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Java具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Java實(shí)現(xiàn)解析dcm醫(yī)學(xué)影像文件并提取文件信息的方法示例
這篇文章主要介紹了Java實(shí)現(xiàn)解析dcm醫(yī)學(xué)影像文件并提取文件信息的方法,結(jié)合實(shí)例形式分析了java基于第三方庫文件針對dcm醫(yī)學(xué)影像文件的解析操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-04-04