SmartUpload 组件是一个免费的上传组件,其主要功能是上传文件,上传图片.
其完整包为:org.lxh.smart.SmartUpload
1. 配置
下载smartupload.jar, 并将其放工webapps的lib目录下
2. 开发
由于图片一般比较大,所以在表单中提交方式设为post,
如要上传图片,则要对表单的数据进行封装.
ENCTYPE="multipart/form-data"
<form action="sample01.jsp" method="post" ENCTYPE="multipart/form-data">
选择要上传的图片:
<input type="file" name="pic">
<input type="submit" value="上传">
</form>
<!--sample01.jsp-->
<jsp:useBean id="smart" scope="page" class="org.lxh.smart.SmartUpload"/>
<%
// 1、上传初始化
smart.initialize(pageContext) ;
// 2、准备上传
smart.upload() ;
// 3、保存上传的文件
smart.save("/upload") ;
%>
<h1>输入的名称为上传后的名称</h1>
<form action="upload.jsp" method="post" ENCTYPE="multipart/form-data">
输入名称:<input type="text" name="name"><br>
选择要上传的图片:
<input type="file" name="pic"><br>
<input type="submit" value="上传">
</form>
<!--upload.jsp-->
<jsp:useBean id="smart" scope="page" class="org.lxh.smart.SmartUpload"/>
<%
// 1、上传初始化
smart.initialize(pageContext) ;
// 2、准备上传
smart.upload() ;
// 3、保存上传的文件
// smart.save("/upload") ;
String ext = smart.getFiles().getFile(0).getFileExt() ;
%>
<%
String name = smart.getRequest().getParameter("name") ;
%>
<%
// 保存文件
smart.getFiles().getFile(0).saveAs("/upload/"+name+"."+ext) ;
%>
PhotoForm photoForm = new PhotoForm();
SmartUpload su = new SmartUpload();
Integer maxID = 0;
if(photoDao.MaxQueryID() != null){
maxID = photoDao.MaxQueryID();
}
String result = "上传的图片大小和格式有问题, 上传失败!";
String type= null;
String imageType[] = {"JPG","jpg","gif","bmp","BMP"}; //可以上传的图片类型
String filedir = "file/";
long maxSize = 2 * 1024 * 1024; //最多可以上传2M
try{
su.initialize(this.getServletConfig(), request, response);
su.setMaxFileSize(maxSize);
su.upload(); //上传文件
Files files = su.getFiles(); //获得所有的文件
for(int i = 0; i<files.getCount(); i++){ //逐个获得上传的图片
File singlefile = files.getFile(i);
type = singlefile.getFileExt(); //获得图片的扩展名
for(int ii = 0; ii<imageType.length; ii++){
if(imageType[ii].equals("type")){ //如果上传的图片的扩展名是上面的五种类型
if(!singlefile.isMissing()){ //如果选择了文件
String photoTime = su.getRequest().getParameter("photoTime");
String photoDescription = su.getRequest().getParameter("photoDescription");
photoForm.setPhotoTime(photoTime);
photoForm.setPhotoDescription(photoDescription);
filedir = filedir + maxID + "." + type; //路径和文件名
photoForm.setPhotoAddress(filedir);
singlefile.saveAs(filedir, File.SAVEAS_VIRTUAL);
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
PhotoForm 有 photoTime, photoDescription, photoAddress
photoDao是封装方法类. 是数据库和Form打交道的类.