SmartUpload组件控制文件上传
?
HTML:
??<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();
?}