SmartUpload組件控制文件上傳
<form action="upload/doUpload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="myfile"/><br />
<input type="file" name="myfile2" /><br />
描述:<input type="text" name="desc" /><br />
<input type="submit"/>
</form>
form表單屬性必須定義method="post" enctype="multipart/form-data"
JSP:
<%@page import="com.jspsmart.upload.SmartUpload"%>
<%@page import="com.jspsmart.upload.File"%>
<%
SmartUpload su = new SmartUpload();
//初始化
su.initialize(pageContext); //內置對象pageContext作為參數
String allowed="jpg,bmp,txt";
su.setAllowedFilesList(allowed); //設置允許上傳的擴展名
String unallowed="bat";
su.setDeniedFilesList(unallowed); //不允許上傳
su.setMaxFileSize(1024*1024*2); //最大上傳2M
try{
su.upload(); //上傳到內存
for (int i = 0; i < su.getFiles().getCount(); i++) { //多個上傳
File file = su.getFiles().getFile(i); //取得單個文件上傳信息
if(file.isMissing()) //判斷是否為空上傳項
continue;
String desc = su.getRequest().getParameter("desc"); //在upload()方法之后才可使用,獲取表單信息
out.print("上傳描述:"+desc);
File file = su.getFiles().getFile(i); //取得單個文件上傳信息
String filePath = "file/";
filePath += file.getFileName(); //設置文件在服務器保存位置
file.saveAs(filePath,SmartUpload.SAVE_VIRTUAL); //文件另存到tomcat部署的項目文件夾中,不是當前項目物理位置
//如果保存絕對路徑,
//file.saveAs(filePath,SmartUpload.SAVE_PHYSICAL);
out.print(filePath);
}
}catch(Exception e){
out.write(e.toString());
e.printStackTrace();
}
%>
Servlet:實現上傳
<form action="servlet/DoUpload" method="post" enctype="multipart/form-data">
--------------------------
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(), request, response); //初始化
String allowed = "jpg,bmp,ico,png";
su.setAllowedFilesList(allowed);
String unallowed = "bat,jsp,aspx,asp,txt";
try {
su.setDeniedFilesList(unallowed);
} catch (SQLException e) {
e.printStackTrace();
}
su.setMaxFileSize(1024*1024*2);
try {
su.upload();
for(int i =0; i<su.getFiles().getCount(); i++){
File file = su.getFiles().getFile(i);
if(file.isMissing())
continue;
String desc = su.getRequest().getParameter("desc");
out.print(desc);
String fileName = "d:/file/"; //路徑必須存在,否則異常
fileName += file.getFileName();
out.print(fileName);
file.saveAs(fileName,SmartUpload.SAVE_PHYSICAL);
}
} catch (SmartUploadException e) {
out.print(e.toString());
e.printStackTrace();
}
out.flush();
out.close();
}