1. 到網上下載兩個包
第一個叫做commons-fileupload-1.2.1.jar
第二個叫做commons-io-1.4.jar
首先我們創建一個名爲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"));
}
}
}
%>
上傳的文件的目錄在tomocat的安裝目錄下此項目的根目錄下例如D:\software\Tomcat 6.0\webapps\fileUpload,看看文件是不是已經在你創建的文件夾下了!