smartupload是一个系统提供的jar包,在非框架开发中非常好用
上传文件时表单必须封装。
封装形式;<form action = "xxx.jsp", method = "post" enctype = "multipart/form-data">按照二进制形式进行提交
要上传文件,必须先建立一个upload的文件夹,这个文件夹保存在WEB根目录下。
代码步骤:
- 实例化SmartUpload对象
- 初始化上传的操作
- 准备文件
- 保存文件
上传文件:
smart_demo1.html
<html>
<head><title>www.thystar.com</title></head>
<body>
<form action = "smart_demo1.jsp", method = "post" enctype = "multipart/form-data">
选择上传文件:<input type="file" name = "pic">
<input type="submit" value="上传">
</form>
</body>
</html>
smart_demo1.jsp
<%@ page contentType="text/html" pageEncoding = "GBK"%>
<%@ page import = "org.lxh.smart.*"%> //将jar包解压放到WEB-INF的classes文件夹下
<html>
<head><title>www.thystar.com</title></head>
<body>
<%
SmartUpload smart = new SmartUpload(); //实例化SmartUpload对象
smart.initialize(pageContext); //初始化上传操作
smart.upload(); //上传准备
smart.save("upload");//上传准备
%>
</body>
</html>
但是,表单一旦上传,就无法使用request.getParameter()接受参数,所以使用String str = smart.getRequest().getParameter("xxx")接收,这段代码在samrt.upload()后。
FileUpload 使用
FileUpload 主要用于框架开发
FileUpload上传的步骤
- 创建磁盘工厂:DistFileItemFactory fac = new DistFileItemFactory()
- 创建处理工具:ServletFileUpload upload = new ServletFileUpload(fac)
- 设置上传文件大小:upload.setFileSizeMax(xxxxxxxxx);
- 接收全部内容: List<FileItem>items = upload.parseRequst(request);
demo.html
<html>
<head><title>www.thystar.com</title></head>
<body>
<form action = "demo1.jsp", method = "post" enctype = "multipart/form-data">
姓名:<input type="text", name = "uname"><br>
照片:<input type="file" name = "pic"><br>
<input type="submit" value="上传">
<input type="reset" value="重置">
</form>
</body>
</html>
demo.jsp
<%@ page contentType="text/html" pageEncoding = "GBK"%>
<%@ page import = "java.util.*"%>
<%@ page import = "org.apache.commons.fileupload.*"%>
<%@ page import = "org.apache.commons.fileupload.disk.*"%>
<%@ page import = "org.apache.commons.fileupload.servlet.*"%>
<html>
<head><title>www.thystar.com</title></head>
<% request.setCharacterEncoding("GBK");%>
<body>
<%
DiskFileItemFactory factory = new DiskFileItemFactory() ;
ServletFileUpload upload = new ServletFileUpload(factory) ;
upload.setFileSizeMax(3 * 1024 * 1024);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while(iter.hasNext()){
FileItem item = iter.next();
String filedName = item.getFieldName();
%>
<ul><h4>表单控件名称:<%=filedName%>---> <%=item.isFormField()%></h4>
<%
if(!item.isFormField()){
String fileName = item.getName();
String contentType = item.getContentType();
long sizeInBytes = item.getSize();
%>
<li>上传文件名称:<%=fileName%>
<li>上传文件类型:<%=contentType%>
<li>上传文件大小:<%=sizeInBytes%>
<%
}else{
String value = item.getString();
%>
<li>普通参数:<%=value%>
<%
}
%>
</ul>
<%
}
%>
</body>
</html>
《Java Web开发实战经典--基础篇》