1. 程式人生 > 程式設計 >java eclipse 中檔案的上傳和下載示例解析

java eclipse 中檔案的上傳和下載示例解析

檔案的上傳與下載(一)

在實現檔案上傳和下載之前我們需要做一些準備工作,在Apache官網去下載檔案上傳下載的兩個元件,下載連結這裡給出:common-fileupload元件下載:http://commons.apache.org/proper/commons-fileupload/

common-io元件下載:http://commons.apache.org/proper/commons-io/根據自己需求下載對應版本

一、建立工程

將所需要的兩個開發包匯入到工程專案中如圖:

java eclipse 中檔案的上傳和下載示例解析

二、程式碼編寫

1.前端頁面程式碼

1). 在WebRoot目錄下新建一個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).新建一個fileUploadResult.jsp頁面用來顯示結果資訊

<%@ 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,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 + "目錄不存在,需要建立!");
   //建立目錄
   file.mkdir();
  }
  //訊息提示
  String message = "";
  try{
   //使用Apache檔案上傳元件處理檔案上傳步驟:
   //1.建立一個DiskFileItemFactory工廠
   DiskFileItemFactory factory = new DiskFileItemFactory();
   //2.建立一個檔案上傳解析器
   ServletFileUpload upload = new ServletFileUpload(factory);
   //解決中文亂碼
   upload.setHeaderEncoding("UTF-8");
   //3.判斷提交的資料普通表單的資料還是帶檔案上傳的表單
   if(!upload.isMultipartContent(request)){
    //如果是表單資料普通表單,則按照傳統方式獲取資料
    return ;
   }
   //4.使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
   List<FileItem> list = upload.parseRequest(request);
   for(FileItem item : list){
    //如果fileItem中封裝的是普通輸入項的資料
    if(item.isFormField()){
     //獲取欄位名字
     String name = item.getFieldName();
     //解決普通輸入項中中文亂碼問題
     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;
     }
     //注意:不同的瀏覽器提交的檔名稱是不一樣的,有些瀏覽器提交的檔案會帶有路徑,如“D:\\project\WebRoot\hello.jsp”,有一些是單純的檔名:hello.jsp
     //去掉獲取到檔名中的路徑名,保留單純的檔名
     filename = filename.substring(filename.lastIndexOf("\\") + 1);
     //獲取item中的上傳檔案的輸入流
     InputStream in = item.getInputStream();
     //建立一個檔案輸入流
     FileOutputStream out = new FileOutputStream(path + "\\" + filename);
     //建立一個緩衝區
     byte buffer[] = new byte[1024];
     //判斷輸入流中的資料是否已經讀取完畢的標誌位
     int len = 0;
     //迴圈將輸入流讀入到緩衝區當中,(len = in.read(buffer)>0)就表示in裡面還有資料存在
     while((len = in.read(buffer)) > 0){
      //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(path+"\\"+filename)當中
      out.write(buffer,len);
     }
     //關閉輸入流
     in.close();
     //關閉輸出流
     out.close();
     //刪除處理檔案上傳生成的臨時檔案
     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>

結果:

java eclipse 中檔案的上傳和下載示例解析

java eclipse 中檔案的上傳和下載示例解析

到此這篇關於eclipse java中檔案的上傳和下載示例解析的文章就介紹到這了,更多相關eclipse java中檔案的上傳和下載內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!