轉載于 http://www.ojava.net/read.php?tid=7130
本教程以Apache組織的commons項目中的FileUpload項目做為jsp的文件上傳組件,FileUpload項目完全尊守RFC1867規范中
關于在HTTP request 中通過Post方法提交文件的規范,該項目性能穩定快速,易于部署和使用.
本次教程以前端jsp + 后端 servlet的方式上傳文件,你也可以完全在jsp中實現而不用servlet.
在開始之前你要準備以下幾個東西:
1. commons-FileUpload 1.2 包
下載地址:
http://jakarta.apache.org/commons/fileupload/
2. commons-IO 1.3.1 包
下載地址:
http://jakarta.apache.org/commons/io/
3. Commons-BeanUtils 1.7 包
下載地址:
http://jakarta.apache.org/commons/beanutils/
有了上面這些東西我們就可以開始了
===============================================================================
1. 新建一個叫upload的WEB項目(我用的是Lomboz3.2開發環境)
2. 把上面下載下來的包分別解壓并拷貝*.jar的文件到上面那個項目的WEB-INF/lib目錄中
3.接下來我們要準備一份如下內容的upload.jsp文件,用來選擇要上傳的文件,
<html>
<head>
<title>Jsp+Servlet upload file</title>
</head>
<body>
<form name="upform" action="UploadServlet" method="POST" enctype="multipart/form-data">
<input type ="file" name="file1" id="file1"/><br/>
<input type ="file" name="file2" if="file2"/><br/>
<input type ="file" name="file3" id="file3"/><br/>
<input type="submit" value="Submit" /><br/>
<input type="reset" />
</form>
</body>
</html>
上面文件中有幾個需要注意的地方就是
1. action="UploadServlet" 必須和后面的web.xml配置文件中對servlet映射必須保持一致.
2. method="POST" 這里必須為"POST"方式提交不能是"GET".
3. enctype="multipart/form-data" 這里是要提交的內容格式,表示你要提交的是數據流,而不是普通的表單文本.
4. file1,file2,file3表示你要3個文件一起上傳,你也可以一次只上傳一個文件.
===================================================================================
接下來我們要寫一個與上面這個upload.jsp配套的servlet程序,就叫做UploadServlet.java吧
以下是該servlet的詳細代碼:
看上去有點長,不過并不復雜,很容易明白的.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
/**
* Servlet implementation class for Servlet: UploadServlet
*
*/
public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
File tmpDir = null;//初始化上傳文件的臨時存放目錄
File saveDir = null;//初始化上傳文件后的保存目錄
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory dff = new DiskFileItemFactory();//創建該對象
dff.setRepository(tmpDir);//指定上傳文件的臨時目錄
dff.setSizeThreshold(1024000);//指定在內存中緩存數據大小,單位為byte
ServletFileUpload sfu = new ServletFileUpload(dff);//創建該對象
sfu.setFileSizeMax(5000000);//指定單個上傳文件的最大尺寸
sfu.setSizeMax(10000000);//指定一次上傳多個文件的總尺寸
FileItemIterator fii = sfu.getItemIterator(request);//解析request 請求,并返回FileItemIterator集合
while(fii.hasNext()){
FileItemStream fis = fii.next();//從集合中獲得一個文件流
if(!fis.isFormField() && fis.getName().length()>0){//過濾掉表單中非文件域
String fileName = fis.getName().substring(fis.getName().lastIndexOf(""""));//獲得上傳文件的文件名
BufferedInputStream in = new BufferedInputStream(fis.openStream());//獲得文件輸入流
BufferedOutputStream out = new BufferedOutputStream(new
FileOutputStream(new File(saveDir+fileName)));//獲得文件輸出流
Streams.copy(in, out, true);//開始把文件寫到你指定的上傳文件夾
}
}
response.getWriter().println("File upload successfully!!!");//終于成功了,還不到你的上傳文件中看看,你要的東西都到齊了嗎
}
}catch(Exception e){
e.printStackTrace();
}
}
public void init() throws ServletException {
/* 對上傳文件夾和臨時文件夾進行初始化
*
*/
super.init();
String tmpPath = "c:""tmpdir";
String savePath = "c:""updir";
tmpDir = new File(tmpPath);
saveDir = new File(savePath);
if(!tmpDir.isDirectory())
tmpDir.mkdir();
if(!saveDir.isDirectory())
saveDir.mkdir();
}
}
========================================================================================================
upload.jsp文件有了,配套的servlet也有了,現在最后剩下的就是怎么讓它們配合工作了,
接著我們把WEB-INF/web.xml文件請出來,并在該文件中加入以下內容:
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
寫好以后再點擊"保存"
==========================================================================================================
把你的upload項目整個拷貝到tomcat的webapps目錄下,啟動tomcat.
打開IE瀏覽器在地址欄中輸入
http://localhost:8080/upload/upload.jsp
怎么樣看到上傳文件的輸入框了嗎? 什么,沒有看到,出錯了! 你仔細檢查一下步驟有沒有對.
好了,現在我們點擊頁面上的"瀏覽"按鈕,找到我們要上傳的文件,最后點擊"Submit",太激動了,還不看一下你的c:"updir里面有沒有你要的東西.