1. 程式人生 > >【轉載】使用jsp實現檔案上傳到伺服器或者從伺服器上下載檔案到本地計算機完整說明版

【轉載】使用jsp實現檔案上傳到伺服器或者從伺服器上下載檔案到本地計算機完整說明版

很多同學在使用jsp實現檔案上傳到伺服器或者從伺服器上下載檔案到本地計算機這方面不是很瞭解,今天在這裡我會幫助大家慢慢的實現這一功能。

準備工作:

1.到網上下載兩個包

第一個叫做commons-fileupload-1.2.1.jar

第二個叫做commons-io-1.3.2.jar

2.建一個專案用來實現檔案上傳和下載

我建立的Web專案名為fileUpload,截圖如下

3.我們把從網上下載下來的包copyWebRoot目錄下Web-INF下的子目錄lib目錄裡

然後開啟Referenced Libraries,你會看見兩個包已經存在於裡面了。

下面我們開始實現檔案上傳

1. 首先我們建立一個名為

uploadFile.jsp的頁面,如下圖:

點選瀏覽,可以出現以下畫面

原始碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

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>實現檔案上傳到伺服器</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>

<form action="doFileUpload.jsp" method="post" enctype="multipart/form-data">

檔案:<input type="file" name="chooseFile"/></br>

姓名:<input type="text" name="userName"/></br>

<input type="submit" value="提交">

</form>

</body>

</html>

注意:form表單裡的enctype=”multipart/form-data”這一屬性一定要寫,這是用來標明此表單的型別是檔案型別的。

2.建立另一個jsp頁面用來處理檔案上傳頁面(實現功能),名為doFileUpload.jsp一定要和form表單裡action的值相同才行

原始碼和註釋如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>

<%@page import="org.apache.commons.fileupload.FileItemFactory"%>

<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>

<%@page import="org.apache.commons.fileupload.FileItem"%>

<%@page import="java.io.File"%>

<%

//先判斷是否是檔案上傳型別enctype="multipart/form-data"

boolean isFileUpload = ServletFileUpload.isMultipartContent(request);

//如果是檔案上傳型別

if(isFileUpload){

//得到檔案上傳工廠

FileItemFactory factory = new DiskFileItemFactory();

//處理檔案上傳核心類

ServletFileUpload fileUpload = new ServletFileUpload(factory);

//設定檔案上傳類的編碼格式

fileUpload.setHeaderEncoding("UTF-8");

// 集合資料 :FileItem物件注意: 每一個表單域對應一個 FileItem物件(封裝)

List<FileItem> fileItemList = fileUpload.parseRequest(request);

//遍歷fileItemList

for(FileItem item: fileItemList){

//如果這個文字域是檔案型別的

if(!item.isFormField()){

//得到文字域的value值,即路徑+檔名

String value = item.getName();

//得到檔名

String fileName = value.substring(value.lastIndexOf("\\")+1);

//得到上傳的檔案型別

//String fileType = fileName.substring(fileName.lastIndexOf("."));

//給檔案重新命名日期+檔名

fileName = new Date().getTime() + fileName;

//得到伺服器的根路徑

String rootPath = request.getRealPath("/");

//指定檔案存放路徑

String realPath = rootPath+"/"+"upload";

//定義檔案存放的目錄,注意目錄也是檔案

File file = new File(realPath);

//如果目錄不存在

if(!file.isDirectory()){

//建立檔案上傳目錄

file.mkdirs();

}

File newFile = new File(realPath+"/"+fileName);

//newFile檔案中寫入資料

item.write(newFile);

}else {//如果不是檔案上傳的文字域,把輸入的內容顯示在頁面上

out.print("name=" + new String(

item.getFieldName().getBytes("ISO-8859-1"),"utf-8")

+",value="+ new String(

item.getString().getBytes("ISO-8859-1"),"utf-8"));

}

}

}

%>

OK,大功告成了!把專案釋出到tomocat裡,然後啟動tomocat即可訪問了,上傳的檔案的目錄在tomocat的安裝目錄下此專案的根目錄下例如D:\software\Tomcat 6.0\webapps\fileUpload,看看檔案是不是已經在你建立的資料夾下了!

檔案下載

建立download.jsp檔案,原始碼如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@page import="java.io.File"%>

<%@page import="java.io.FileInputStream"%>

<%@pageimport="com.sun.xml.internal.messaging.saaj.util.ByteOutputStream"%>

<%@page import="java.io.OutputStream"%>

<%@page import="com.yinhe.entity.Users"%>

<%

//得到你要下載的檔名(由前一個頁面傳過來)

String fileName = new String

(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");

//得到專案在tomcat 中的更路徑

String realPath = request.getRealPath("/");

//得到檔案在伺服器中的路徑

String path = realPath+ "upload/" + fileName;// 這就是檔案所在完整路徑

//清空response 所有資訊

response.reset();

//設定IE瀏覽器內容型別表示為下載

response.setContentType("application/x-download;charset=UTF-8");

//設定IE瀏覽器的

response.setHeader("Content-Disposition","attachment;filename="+ fileName);

//從伺服器上讀取檔案

File file=new File(path);response.setContentLength(Integer.valueOf(((Long)file.length()).toString()));

//輸入流讀取目標檔案

FileInputStreamfis=new FileInputStream(file);

int len=-1;

byte[] data=newbyte[1024];

ByteOutputStream bos=new ByteOutputStream(1024);

// 檔案讀到最末尾返回 -1

while((len=fis.read(data))!=-1)

{

//將伺服器中的資料轉換成二進位制陣列放入記憶體中

bos.write(data,0,len);

}

//伺服器上的檔案轉換成二進位制陣列OutPutStream 輸出流寫入對應檔案中

OutputStream os= response.getOutputStream();

//從伺服器拿到資料向客戶端進行寫入

os.write(bos.getBytes());

//清空記憶體檔案向客戶端寫入

os.flush();

//關閉輸出流

os.close();

//關閉輸入流

fis.close();

%>