package?com.imooc.servlet;
import?java.io.File;
import?java.io.IOException;
import?java.sql.SQLException;
import?javax.servlet.ServletException;
import?javax.servlet.annotation.WebServlet;
import?javax.servlet.http.HttpServlet;
import?javax.servlet.http.HttpServletRequest;
import?javax.servlet.http.HttpServletResponse;
import?com.jspsmart.upload.SmartUpload;
import?com.jspsmart.upload.SmartUploadException;
/**
?*?Servlet?implementation?class?SmartUploadServlet
?*/
@WebServlet("/SmartUploadServlet")
public?class?SmartUploadServlet?extends?HttpServlet?{
private?static?final?long?serialVersionUID?=?1L;
???????
????/**
?????*?@see?HttpServlet#HttpServlet()
?????*/
????public?SmartUploadServlet()?{
????????super();
????????//?TODO?Auto-generated?constructor?stub
????}
/**
?*?@see?HttpServlet#doGet(HttpServletRequest?request,?HttpServletResponse?response)
?*/
protected?void?doGet(HttpServletRequest?request,?HttpServletResponse?response)?throws?ServletException,?IOException?{
//?TODO?Auto-generated?method?stub
doPost(request,response);
}
/**
?*?@throws?ServletException?
?*?@throws?IOException?
?*?@see?HttpServlet#doPost(HttpServletRequest?request,?HttpServletResponse?response)
?*/
protected?void?doPost(HttpServletRequest?request,?HttpServletResponse?response)?throws?ServletException,?IOException?{
//?TODO?Auto-generated?method?stub
//設(shè)置文件保存路徑
String?path?=?getServletContext().getRealPath("/")+"image";
File?file?=?new?File(path);
if(file.exists()){
file.mkdirs();
}
SmartUpload?su?=?new?SmartUpload();
String?result?=?"文件上傳成功";
//初始化SmartUpload對象?getServletConfig()返回一個ServletConfig對象,通過該對象可以獲得該servlet的初始化參數(shù)
su.initialize(getServletConfig(),request,?response);
//設(shè)置上傳文件的大小為10M
su.setMaxFileSize(1024*1024*10);
//設(shè)置上傳文件的總大小為100M
su.setTotalMaxFileSize(1024*1024*100);
//設(shè)置允許上傳文件的類型
su.setAllowedFilesList("txt,jpg,png,gif");
//設(shè)置不允許上傳類型
try?{
// su.setDeniedFilesList("jsp,js,rar");
//上傳文件
su.upload();
int?count?=?su.save(path);
System.out.println("上傳成功了"+count+"個文件");
// }?catch?(SQLException?e)?{
// //?TODO?Auto-generated?catch?block
// result?=?"上傳失敗";
// e.printStackTrace();
}?catch?(Exception?e)?{//這兒不能寫成SmartUploadException?如果這樣就會轉(zhuǎn)發(fā)到異常信息頁面而不是轉(zhuǎn)發(fā)到02.jsp頁面
//?TODO?Auto-generated?catch?block
System.out.println(e.getMessage());
if(e.getMessage().indexOf("1015")!=-1){
result?=?"上傳失?。荷蟼魑募愋筒徽_";
}else?if(e.getMessage().indexOf("1010")!=-1){
result?=?"上傳失?。荷蟼魑募愋筒徽_";
}else?if(e.getMessage().indexOf("1005")!=-1){
result?=?"上傳失敗:大小超過單個上傳文件的最大值";
}else?if(e.getMessage().indexOf("1110")!=-1){
result?=?"上傳失?。嚎偞笮〕^所有上傳文件的最大值";
}
e.printStackTrace();
}
request.setAttribute("result",?result);
request.getRequestDispatcher("jsp/02.jsp").forward(request,?response);
}
}
2016-09-20
這個Exception是最大的異常 只要是出現(xiàn)異常就會打印堆棧,可是寫成SmartException的話 一旦出現(xiàn)其他異常就還需要另外一個try catch。 代碼看起來會很嵌套繁瑣,這個只是練習所以這么寫的
2016-09-20
這個Exception是最大的異常 只要是出現(xiàn)異常就會打印堆棧,可是寫成SmartException的話 一旦出現(xiàn)其他異常就還需要另外一個try catch 代碼看起來會很嵌套繁瑣,這個只是練習所以這么寫的