JSP文件上传程序实例
㈠ 表单要求
对于上传文件的form表单,有两个要求:
1、method应用post,即method="post"。
2、增加属性:enctype="multipart/form-data"
下面是一个用于上传文件的form表单的例子:
<form method="post" enctype="multipart/form-data" action="/jsp教程smartupload/upload.jsp"> <input type="file" name="myfile"> <input type="submit"> </form> |
㈡ 上传的例子
1、上传页面upload.html
本页面提供表单,让用户选择要上传的文件,点击"上传"按钮执行上传操作。
页面源码如下:
<!--文件名:upload.html--> <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>文件上传 - JSP教程:http://www.javaweb.cc</title> <meta http-equiv="content-type" content="text/html; charset=gb2312"> </head> <body> <p> </p> <p align="center">上传文件选择</p> <form method="post" action="jsp/do_upload.jsp" enctype="multipart/form-data"> <input type="hidden" name="test" value="good"> <table width="75%" border="1" align="center"> <tr> <td><div align="center">1、 <input type="file" name="file1" size="30"> </div></td> </tr> <tr> <td><div align="center">2、 <input type="file" name="file2" size="30"> </div></td> </tr> <tr> <td><div align="center">3、 <input type="file" name="file3" size="30"> </div></td> </tr> <tr> <td><div align="center">4、 <input type="file" name="file4" size="30"> </div></td> </tr> <tr> <td><div align="center"> <input type="submit" name="submit" value="上传它!"> </div></td> </tr> </table> </form> </body> </html> |
2、上传处理页面do_upload.jsp
本页面执行文件上传操作。页面源码中详细介绍了上传方法的用法,在此不赘述了。
页面源码如下:
<%--文件名:do_upload.jsp--%> <%@ page contenttype="text/html; charset=gb2312" language="java" import="java.util.*,com.jsps教程mart.upload.*" errorpage="" %> <html> <head> <title>文件上传处理页面</title> <meta http-equiv="content-type" content="text/html; charset=gb2312"> </head> <body> <% // 新建一个smartupload对象 smartupload su = new smartupload(); // 上传初始化 su.initialize(pagecontext); // 设定上传限制 // 1.限制每个上传文件的最大长度。 // su.setmaxfilesize(10000); // 2.限制总上传数据的长度。 // su.settotalmaxfilesize(20000); // 3.设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。 // su.setallowedfileslist("doc,txt"); // 4.设定禁止上传的文件(通过扩展名限制),禁止上传带有exe,bat, jsp,htm,html扩展名的文件和没有扩展名的文件。 // su.setdeniedfileslist("exe,bat,jsp,htm,html,,"); // 上传文件 su.upload(); // 将上传文件全部保存到指定目录 int count = su.save("/upload"); out.println(count+"个文件上传成功!<br>");
|