package com.future.zfs.util;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
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.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@SuppressWarnings("serial")
public class FileUploadServlet extends HttpServlet {
final long MAX_SIZE = 10 * 1024 * 1024;// 設(shè)置上傳文件最大為 10M
// 允許上傳的文件格式的列表
final String[] allowtype = new String[] {"jpg","jpeg","gif","txt","doc","docx","mp3","wma","m4a","xls"};
public FileUploadServlet() {
super();
}
public void destroy() {
super.destroy();
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// 設(shè)置字符編碼為UTF-8, 這樣支持漢字顯示
response.setCharacterEncoding("UTF-8");
// 實(shí)例化一個(gè)硬盤文件工廠,用來配置上傳組件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 設(shè)置上傳文件時(shí)用于臨時(shí)存放文件的內(nèi)存大小,這里是4K.多于的部分將臨時(shí)存在硬盤
dfif.setRepository(new File(request.getRealPath("/")
+ "uploadtemp"));// 設(shè)置存放臨時(shí)文件的目錄,web根目錄下的uploadtemp目錄
// 用以上工廠實(shí)例化上傳組件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 設(shè)置最大上傳尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
// 從request得到 所有 上傳域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {// 處理文件尺寸過大異常
if (e instanceof SizeLimitExceededException) {
out.println("{message:'文件尺寸超過規(guī)定大小:"+MAX_SIZE+"字節(jié)'}");
return;
}
e.printStackTrace();
}
// 沒有文件上傳
if (fileList == null || fileList.size() == 0) {
out.println("{message:'請(qǐng)選擇上傳文件'}");
return;
}
// 得到所有上傳的文件
Iterator fileItr = fileList.iterator();
// 循環(huán)處理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到當(dāng)前文件
fileItem = (FileItem) fileItr.next();
// 忽略簡(jiǎn)單form字段而不是上傳域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路徑
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0) {
out.println("{message:'請(qǐng)選擇上傳文件'}");
return;
}
// 得到去除路徑的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的擴(kuò)展名(無擴(kuò)展名時(shí)將得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒絕接受規(guī)定文件格式之外的文件類型
int allowFlag = 0;
int allowedExtCount = allowtype.length;
for (; allowFlag < allowedExtCount; allowFlag++) {
if (allowtype[allowFlag].equals(t_ext))
break;
}
if (allowFlag == allowedExtCount) {
String message = "";
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++){
message+="*." + allowtype[allowFlag]
+ " ";
}
out.println("{message:'請(qǐng)上傳以下類型的文件"+message+"'}");
return;
}
long now = System.currentTimeMillis();
// 根據(jù)系統(tǒng)時(shí)間生成上傳后保存的文件名
String prefix = String.valueOf(now);
// 保存的最終文件完整路徑,保存在web根目錄下的upload目錄下
String u_name = request.getRealPath("/") + "upload/"
+ prefix + "." + t_ext;
//原來的文件名
path=request.getRealPath("/") + "upload/"+path;
try {
// 保存文件
fileItem.write(new File(path));
response.setStatus(200);
out.println("{message:\"文件上傳成功. 已保存為: " + prefix + "." + t_ext
+ " 文件大小: " + size + "字節(jié)\"}");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
web.xml
<servlet>
<servlet-name>fileUploadServlet</servlet-name>
<servlet-class>com.future.zfs.util.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUploadServlet</servlet-name>
<url-pattern>/fileUploadServlet</url-pattern>
</servlet-mapping>
上傳頁(yè)面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$("#loading")
.ajaxStart(function(){
$(this).show();
})//開始上傳文件時(shí)顯示一個(gè)圖片
.ajaxComplete(function(){
$(this).hide();
});//文件上傳完成將圖片隱藏起來
$.ajaxFileUpload
(
{
url:'fileUploadServlet',//用于文件上傳的服務(wù)器端請(qǐng)求地址
secureuri:false,//一般設(shè)置為false
fileElementId:'file',//文件上傳空間的id屬性 <input type="file" id="file" name="file" />
dataType: 'json',//返回值類型 一般設(shè)置為json
success: function (data, status) //服務(wù)器成功響應(yīng)處理函數(shù)
{
//alert(data.message);//從服務(wù)器返回的json中取出message中的數(shù)據(jù),其中message為在struts2中定義的成員變量
$('#myspan').html(data.message);
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
//alert(data.error);
$('#myspan').html(data.message);
}else
{
//alert(data.message);
$('#myspan').html(data.message);
}
}
},
error: function (data, status, e)//服務(wù)器響應(yīng)失敗處理函數(shù)
{
//alert(e);
$('#myspan').html(e);
}
}
)
return false;
}
</script>
</head>
<body>
<img src="images/loading.gif" id="loading" style="display: none;">
<span style="color: red;" id="myspan"></span><br/>
<input type="file" id="file" name="file" />
<br />
<input type="button" value="上傳" onclick="return ajaxFileUpload();">
<a href="fileDownLoadServlet?filename=通訊錄.xls">哈哈,測(cè)試文件下載</a>
</body>
</html>
需要注意的是:在使用ajaxFileUpload基于servlet上傳時(shí)需要設(shè)置response.setContentType("text/html");盡管dataType: 'json'設(shè)置為json仍要設(shè)置response.setContentType("text/html");否則獲取不到服務(wù)器端返回的數(shù)據(jù)以及會(huì)彈出一個(gè)對(duì)話框
這點(diǎn)與基于struts2的ajaxFileUpload上傳是不一樣的,可以參考之前寫的
http://m.tkk7.com/sxyx2008/archive/2010/11/02/336826.html