java eclipse 中文件的上傳和下載示例解析
文件的上傳與下載(一)
在實(shí)現(xiàn)文件上傳和下載之前我們需要做一些準(zhǔn)備工作,在Apache官網(wǎng)去下載文件上傳下載的兩個(gè)組件,下載鏈接這里給出:common-fileupload組件下載:http://commons.apache.org/proper/commons-fileupload/
common-io組件下載:http://commons.apache.org/proper/commons-io/根據(jù)自己需求下載對(duì)應(yīng)版本
一、創(chuàng)建工程
將所需要的兩個(gè)開發(fā)包導(dǎo)入到工程項(xiàng)目中如圖:
二、代碼編寫
1.前端頁面代碼
1). 在WebRoot目錄下新建一個(gè)fileUpload.jsp頁面,用來上傳文件
<%@ page language='java' import='java.util.*' pageEncoding='GB18030'%><%String path = request.getContextPath();String basePath = request.getScheme()+'://'+request.getServerName()+':'+request.getServerPort()+path+'/';%><!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'><html> <head> <base href='http://www.piao2010.com/bcjs/<%=basePath%>'> <title>My JSP ’fileUpload.jsp’ starting page</title> <meta http-equiv='pragma' content='no-cache'> <meta http-equiv='cache-control' content='no-cache'> <meta http-equiv='expires' content='0'> <meta http-equiv='keywords' content='keyword1,keyword2,keyword3'> <meta http-equiv='description' content='This is my page'> <!-- <link rel='stylesheet' type='text/css' href='http://www.piao2010.com/bcjs/styles.css'> --> </head> <body> <!-- 文件上傳表單的提交方式必須是“post” 編碼類型必須為:enctype='multipart/form-data' --> <form action='UploadServlet' method='post' enctype='multipart/form-data'> username: <input type='text' name='username' /><br> file: <input type='file' name='file'><br> file2: <input type='file' name='file2'><br> <input type='submit' value='上傳文件'> </form> </body></html>
2).新建一個(gè)fileUploadResult.jsp頁面用來顯示結(jié)果信息
<%@ page language='java' import='java.util.*,java.io.*' pageEncoding='GB18030'%><%String path = request.getContextPath();String basePath = request.getScheme()+'://'+request.getServerName()+':'+request.getServerPort()+path+'/';%><!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'><html> <head> <base href='http://www.piao2010.com/bcjs/<%=basePath%>'> <title>My JSP ’fileUploadResult.jsp’ starting page</title> <meta http-equiv='pragma' content='no-cache'> <meta http-equiv='cache-control' content='no-cache'> <meta http-equiv='expires' content='0'> <meta http-equiv='keywords' content='keyword1,keyword2,keyword3'> <meta http-equiv='description' content='This is my page'> <!-- <link rel='stylesheet' type='text/css' href='http://www.piao2010.com/bcjs/styles.css'> --> </head> <body> <%-- <% //獲取流對(duì)象 InputStream inputStream = request.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String buffer = null; while((buffer = br.readLine()) != null){ out.print(buffer + '<br>'); } br.close(); inputStream.close(); %> --%> ${message}<br> EL-username : ${requestScope.username} <br> EL-file1 : ${requestScope.file }<br> EL-file2 : ${requestScope.file2}<br> </body></html>
2. 編寫上傳文件處理的Servlet代碼
1) UploadServlet.java代碼如下:
package com.Servlet;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.List;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class UploadServlet extends HttpServlet { /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳文件的保存目錄,將上傳的文件放在webRoot目錄下(但是一般為了安全放在WEB-INF目錄下,不允許外界直接訪問,保證上傳的安全) String path = this.getServletContext().getRealPath('/upload'); File file = new File(path); //判斷上傳文件的保存目錄是否存在 if(!file.exists() && !file.isDirectory()){ System.out.println(path + '目錄不存在,需要?jiǎng)?chuàng)建!'); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ''; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1.創(chuàng)建一個(gè)DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2.創(chuàng)建一個(gè)文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決中文亂碼 upload.setHeaderEncoding('UTF-8'); //3.判斷提交的數(shù)據(jù)普通表單的數(shù)據(jù)還是帶文件上傳的表單 if(!upload.isMultipartContent(request)){ //如果是表單數(shù)據(jù)普通表單,則按照傳統(tǒng)方式獲取數(shù)據(jù) return ; } //4.使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileItem中封裝的是普通輸入項(xiàng)的數(shù)據(jù) if(item.isFormField()){ //獲取字段名字 String name = item.getFieldName(); //解決普通輸入項(xiàng)中中文亂碼問題 String value = item.getString('UTF-8');//value = new String(value.getBytes('iso8859-1'),'UTF-8'); System.out.println(name + ' = ' + value); }else{ //如果表單中提交的是上傳文件 //獲得上傳的文件名稱 String filename = item.getName(); System.out.println(filename); if(filename == null || filename.trim().equals(' ')){ continue; } //注意:不同的瀏覽器提交的文件名稱是不一樣的,有些瀏覽器提交的文件會(huì)帶有路徑,如“D:projectWebRoothello.jsp”,有一些是單純的文件名:hello.jsp //去掉獲取到文件名中的路徑名,保留單純的文件名 filename = filename.substring(filename.lastIndexOf('') + 1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個(gè)文件輸入流 FileOutputStream out = new FileOutputStream(path + '' + filename); //創(chuàng)建一個(gè)緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀取完畢的標(biāo)志位 int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len = in.read(buffer)>0)就表示in里面還有數(shù)據(jù)存在 while((len = in.read(buffer)) > 0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(path+''+filename)當(dāng)中 out.write(buffer, 0, len); } //關(guān)閉輸入流 in.close(); //關(guān)閉輸出流 out.close(); //刪除處理文件上傳生成的臨時(shí)文件 item.delete(); message = '文件上傳成功!'; } } }catch(Exception e){ message = '文件上傳失敗!'; e.printStackTrace(); } request.setAttribute(message, message); request.getRequestDispatcher('fileUploadResult.jsp').forward(request, response); }}
2)web.xml文件中的配置
<?xml version='1.0' encoding='UTF-8'?><web-app version='3.0' xmlns='http://java.sun.com/xml/ns/javaee' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd'> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.Servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping></web-app>
結(jié)果:
到此這篇關(guān)于eclipse java中文件的上傳和下載示例解析的文章就介紹到這了,更多相關(guān)eclipse java中文件的上傳和下載內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. vue 限制input只能輸入正數(shù)的操作2. Android實(shí)現(xiàn)儀表盤控件開發(fā)3. python 繪制斜率圖進(jìn)行對(duì)比分析4. Python基于traceback模塊獲取異常信息5. 解決Python 函數(shù)聲明先后順序出現(xiàn)的問題6. 利用python+ffmpeg合并B站視頻及格式轉(zhuǎn)換的實(shí)例代碼7. python GUI模擬實(shí)現(xiàn)計(jì)算器8. CVS常用命令速查手冊(cè)9. Android自定義短信倒計(jì)時(shí)view流程分析10. AOP中的主要技術(shù)(二)
