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ù)自己需求下載對應(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="<%=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="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="<%=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="styles.css"> --> </head> <body> <%-- <% //獲取流對象 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對應(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:\\project\WebRoot\hello.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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java利用自定義注解實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)
JSR303是一套JavaBean參數(shù)校驗(yàn)的標(biāo)準(zhǔn),它提供了一系列的校驗(yàn)方式,這些校驗(yàn)方式在javax.validation.constraints包中。本文就來聊聊如何利用它實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)2022-09-09Spring Boot Admin監(jiān)控服務(wù)如何使用
這篇文章主要介紹了Spring Boot Admin監(jiān)控服務(wù)如何使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04Java實(shí)現(xiàn)常用緩存淘汰算法:FIFO、LRU、LFU
在高并發(fā)、高性能的質(zhì)量要求不斷提高時(shí),我們首先會(huì)想到的就是利用緩存予以應(yīng)對。而常用的幾個(gè)緩存淘汰算法有:FIFO、LRU和LFU,本文將為大家詳細(xì)介紹一下這三個(gè)算法并用java實(shí)現(xiàn),感興趣的可以跟隨小編一起學(xué)習(xí)一下2021-12-12SpringBoot整合Flink CDC實(shí)現(xiàn)實(shí)時(shí)追蹤mysql數(shù)據(jù)變動(dòng)
我們將整合Spring Boot和Apache Flink CDC(Change Data Capture)來實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)追蹤,下面是一個(gè)基本的實(shí)踐流程代碼,包括搭建Spring Boot項(xiàng)目、整合Flink CDC以及實(shí)現(xiàn)數(shù)據(jù)變動(dòng)的實(shí)時(shí)追蹤,需要的朋友可以參考下2024-07-07JDBC實(shí)現(xiàn)學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了JDBC實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02Java8中List轉(zhuǎn)換String字符串幾種方式
這篇文章主要給大家介紹了關(guān)于Java8中List轉(zhuǎn)換String字符串的幾種方式,在實(shí)際開發(fā)中經(jīng)常遇到List轉(zhuǎn)為String字符串的情況,文中給出了幾種方法的示例代碼,需要的朋友可以參考下2023-07-07