一、安装篇

  jspSmartUpload是由http://www.jspsmart.com网站开发的一...幸韵录父鎏氐悖?/a>

1、使用简单。在JSP文件中仅仅书写三五行JAVA代码就可以搞定文件的上传或下载,方便。

2、能全程控制上传。利用jspSmartUpload组件提供的对象及其操作方法,可以获得全部上传文件的信息(包括文件名,大小,类型,扩展名,文件数据等),方便存取。

3、能对上传的文件在大小、类型等方面做出限制。如此可以滤掉不符合要求的文件。

4、下载灵活。仅写两行代码,就能把Web服务器变成文件服务器。不管文件在Web服务器的目录下或在其它任何目录下,都可以利用jspSmartUpload进行下载。

5、能将文件上传到数据库中,也能将数据库中的数据下载下来。这种功能针对的是MYSQL数据库,因为不具有通用性,所以本文不准备举例介绍这种用法。

  jspSmartUpload组件可以从
http://www.jspsmart.com网站上自由下载,压缩包的名字是jspsmartupload.zip。下载后,用winzip或winrar将其解压到tomcat的webapps目录下(本文以tomcat服务器为例进行介绍)。解压后,将webapps/jspsmartupload目录下的子目录Web-inf名字改为全大写的WEB-INF,这样一改jspSmartUpload类才能使用。因为Tomcat对文件名大小写敏感,它要求Web应用程序相关的类所在目录为WEB-INF,且必须是大写。接着重新启动Tomcat,这样就可以在JSP文件中使用jspSmartUpload组件了。

  注意,按上述方法安装后,只有webapps/jspsmartupload目录下的程序可以使用jspSmartUpload组件,如果想让Tomcat服务器的所有Web应用程序都能用它,必须做如下工作:

1.进入命令行状态,将目录切换到Tomcat的webapps/jspsmartupload/WEB-INF目录下。

2.运行JAR打包命令:jar cvf jspSmartUpload.jar com

(也可以打开资源管理器,切换到当前目录,用WinZip将com目录下的所有文件压缩成jspSmartUpload.zip,然后将jspSmartUpload.zip换名为jspSmartUpload.jar文件即可。)

3.将jspSmartUpload.jar拷贝到Tomcat的shared/lib目录下。
二、相关类说明篇

㈠ File类

  这个类包装了一个上传文件的所有信息。通过它,可以得到上传文件的文件名、文件大小、扩展名、文件数据等信息。

  File类主要提供以下方法:

1、saveAs作用:将文件换名另存。

原型:

public void saveAs(java.lang.String destFilePathName)



public void saveAs(java.lang.String destFilePathName, int optionSaveAs)

其中,destFilePathName是另存的文件名,optionSaveAs是另存的选项,该选项有三个值,分别是SAVEAS_PHYSICAL,SAVEAS_VIRTUAL,SAVEAS_AUTO。SAVEAS_PHYSICAL表明以操作系统的根目录为文件根目录另存文件,SAVEAS_VIRTUAL表明以Web应用程序的根目录为文件根目录另存文件,SAVEAS_AUTO则表示让组件决定,当Web应用程序的根目录存在另存文件的目录时,它会选择SAVEAS_VIRTUAL,否则会选择SAVEAS_PHYSICAL。

例如,saveAs("/upload/sample.zip",SAVEAS_PHYSICAL)执行后若Web服务器安装在C盘,则另存的文件名实际是c:\upload\sample.zip。而saveAs("/upload/sample.zip",SAVEAS_VIRTUAL)执行后若Web应用程序的根目录是webapps/jspsmartupload,则另存的文件名实际是webapps/jspsmartupload/upload/sample.zip。saveAs("/upload/sample.zip",SAVEAS_AUTO)执行时若Web应用程序根目录下存在upload目录,则其效果同saveAs("/upload/sample.zip",SAVEAS_VIRTUAL),否则同saveAs("/upload/sample.zip",SAVEAS_PHYSICAL)。

建议:对于Web程序的开发来说,最好使用SAVEAS_VIRTUAL,以便移植。

2、isMissing

作用:这个方法用于判断用户是否选择了文件,也即对应的表单项是否有值。选择了文件时,它返回false。未选文件时,它返回true。

原型:public boolean isMissing()

3、getFieldName

作用:取HTML表单中对应于此上传文件的表单项的名字。

原型:public String getFieldName()

4、getFileName

作用:取文件名(不含目录信息)

原型:public String getFileName()

5、getFilePathName

作用:取文件全名(带目录)

原型:public String getFilePathName

6、getFileExt

作用:取文件扩展名(后缀)

原型:public String getFileExt()

7、getSize

作用:取文件长度(以字节计)

原型:public int getSize()

8、getBinaryData

作用:取文件数据中指定位移处的一个字节,用于检测文件等处理。

原型:public byte getBinaryData(int index)。其中,index表示位移,其值在0到getSize()-1之间。

㈡ Files类

  这个类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息。有以下方法:

1、getCount

作用:取得上传文件的数目。

原型:public int getCount()

2、getFile

作用:取得指定位移处的文件对象File(这是com.jspsmart.upload.File,不是java.io.File,注意区分)。

原型:public File getFile(int index)。其中,index为指定位移,其值在0到getCount()-1之间。

3、getSize

作用:取得上传文件的总长度,可用于限制一次性上传的数据量大小。

原型:public long getSize()

4、getCollection

作用:将所有上传文件对象以Collection的形式返回,以便其它应用程序引用,浏览上传文件信息。

原型:public Collection getCollection()

5、getEnumeration

作用:将所有上传文件对象以Enumeration(枚举)的形式返回,以便其它应用程序浏览上传文件信息。

原型:public Enumeration getEnumeration()

㈢ Request类

  这个类的功能等同于JSP内置的对象request。只所以提供这个类,是因为对于文件上传表单,通过request对象无法获得表单项的值,必须通过jspSmartUpload组件提供的Request对象来获取。该类提供如下方法:

1、getParameter

作用:获取指定参数之值。当参数不存在时,返回值为null。

原型:public String getParameter(String name)。其中,name为参数的名字。

2、getParameterValues

作用:当一个参数可以有多个值时,用此方法来取其值。它返回的是一个字符串数组。当参数不存在时,返回值为null。

原型:public String[] getParameterValues(String name)。其中,name为参数的名字。

3、getParameterNames

作用:取得Request对象中所有参数的名字,用于遍历所有参数。它返回的是一个枚举型的对象。

原型:public Enumeration getParameterNames()
㈣ SmartUpload类这个类完成上传下载工作。

A.上传与下载共用的方法:

只有一个:initialize。

作用:执行上传下载的初始化工作,必须第一个执行。

原型:有多个,主要使用下面这个:

public final void initialize(javax.servlet.jsp.PageContext pageContext)

其中,pageContext为JSP页面内置对象(页面上下文)。

B.上传文件使用的方法:

1、upload

作用:上传文件数据。对于上传操作,第一步执行initialize方法,第二步就要执行这个方法。

原型:public void upload()

2、save

作用:将全部上传文件保存到指定目录下,并返回保存的文件个数。

原型:public int save(String destPathName)

和public int save(String destPathName,int option)

其中,destPathName为文件保存目录,option为保存选项,它有三个值,分别是SAVE_PHYSICAL,SAVE_VIRTUAL和SAVE_AUTO。(同File类的saveAs方法的选项之值类似)SAVE_PHYSICAL指示组件将文件保存到以操作系统根目录为文件根目录的目录下,SAVE_VIRTUAL指示组件将文件保存到以Web应用程序根目录为文件根目录的目录下,而SAVE_AUTO则表示由组件自动选择。

注:save(destPathName)作用等同于save(destPathName,SAVE_AUTO)。

3、getSize

作用:取上传文件数据的总长度

原型:public int getSize()

4、getFiles

作用:取全部上传文件,以Files对象形式返回,可以利用Files类的操作方法来获得上传文件的数目等信息。

原型:public Files getFiles()

5、getRequest

作用:取得Request对象,以便由此对象获得上传表单参数之值。

原型:public Request getRequest()

6、setAllowedFilesList

作用:设定允许上传带有指定扩展名的文件,当上传过程中有文件名不允许时,组件将抛出异常。

原型:public void setAllowedFilesList(String allowedFilesList)

其中,allowedFilesList为允许上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想允许上传那些没有扩展名的文件,可以用两个逗号表示。例如:setAllowedFilesList("doc,txt,,")将允许上传带doc和txt扩展名的文件以及没有扩展名的文件。

7、setDeniedFilesList

作用:用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制,则上传时组件将抛出异常。

原型:public void setDeniedFilesList(String deniedFilesList)

其中,deniedFilesList为禁止上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想禁止上传那些没有扩展名的文件,可以用两个逗号来表示。例如:setDeniedFilesList("exe,bat,,")将禁止上传带exe和bat扩展名的文件以及没有扩展名的文件。

8、setMaxFileSize

作用:设定每个文件允许上传的最大长度。

原型:public void setMaxFileSize(long maxFileSize)

其中,maxFileSize为为每个文件允许上传的最大长度,当文件超出此长度时,将不被上传。

9、setTotalMaxFileSize

作用:设定允许上传的文件的总长度,用于限制一次性上传的数据量大小。

原型:public void setTotalMaxFileSize(long totalMaxFileSize)

其中,totalMaxFileSize为允许上传的文件的总长度。
jsp 上传图片并生成缩位图或者加水印
有些网站  动网, 上传图片后加给加上自己的字(是在图片上加的)

 请问在JSP里如何实现??
//添加水印,filePath 源图片路径, watermark 水印图片路径
public static boolean createMark(String filePath,String watermark) {
ImageIcon imgIcon=new ImageIcon(filePath);
Image theImg =imgIcon.getImage();
ImageIcon waterIcon=new ImageIcon(watermark);
Image waterImg =waterIcon.getImage();
int width=theImg.getWidth(null);
int height= theImg.getHeight(null);
BufferedImage bimage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=bimage.createGraphics( );
g.setColor(Color.red);
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null );
g.drawImage(waterImg, 100, 100, null );
g.drawString("12233",10,10); //添加文字
g.dispose();
try{
FileOutputStream out=new FileOutputStream(filePath);
JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(50f, true);
encoder.encode(bimage, param);
out.close();
}catch(Exception e){ return false; }
return true;
}

/////////////////范例////////////////////
package package;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

public class upload
{

private static String newline = "\n";
private String uploadDirectory;
private String ContentType;
private String CharacterEncoding;

public upload()
{
uploadDirectory = ".";
ContentType = "";
CharacterEncoding = "";
}

private String getFileName(String s)
{
int i = s.lastIndexOf("\\");
if(i < 0 || i >= s.length() - 1)
{
i = s.lastIndexOf("/");
if(i < 0 || i >= s.length() - 1)
return s;
}
return s.substring(i + 1);
}

public void setUploadDirectory(String s)
{
uploadDirectory = s;
}

public void setContentType(String s)
{
ContentType = s;
int i;
if((i = ContentType.indexOf("boundary=")) != -1)
{
ContentType = ContentType.substring(i + 9);
ContentType = "--" + ContentType;
}
}

public void setCharacterEncoding(String s)
{
CharacterEncoding = s;
}

public String uploadFile(HttpServletRequest httpservletrequest)
throws ServletException, IOException
{
String s = null;
setCharacterEncoding(httpservletrequest.getCharacterEncoding());
setContentType(httpservletrequest.getContentType());
s = uploadFile(httpservletrequest.getInputStream());
return s;
}

public String uploadFile(ServletInputStream servletinputstream)
throws ServletException, IOException
{
String s = null;
String s1 = null;
byte abyte0[] = new byte[4096];
byte abyte1[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
String s2;
while((s2 = readLine(abyte0, ai, servletinputstream, CharacterEncoding)) != null)
{
int i = s2.indexOf("filename=");
if(i >= 0)
{
s2 = s2.substring(i + 10);
if((i = s2.indexOf("\"")) > 0)
s2 = s2.substring(0, i);
break;
}
}
s1 = s2;
if(s1 != null && !s1.equals("\""))
{
s1 = getFileName(s1);
String s3 = readLine(abyte0, ai, servletinputstream, CharacterEncoding);
if(s3.indexOf("Content-Type") >= 0)
readLine(abyte0, ai, servletinputstream, CharacterEncoding);
File file = new File(uploadDirectory, s1);
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((s3 = readLine(abyte0, ai, servletinputstream, CharacterEncoding)) != null)
{
if(s3.indexOf(ContentType) == 0 && abyte0[0] == 45)
break;
if(s != null)
{
fileoutputstream.write(abyte1, 0, ai1[0]);
fileoutputstream.flush();
}
s = readLine(abyte1, ai1, servletinputstream, CharacterEncoding);
if(s == null || s.indexOf(ContentType) == 0 && abyte1[0] == 45)
break;
fileoutputstream.write(abyte0, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(s != null && abyte1[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(abyte1, 0, ai1[0] - newline.length() * byte0);
if(s3 != null && abyte0[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(abyte0, 0, ai[0] - newline.length() * byte0);
fileoutputstream.close();
}
return s1;
}

private String readLine(byte abyte0[], int ai[], ServletInputStream servletinputstream, String s)
{
ai[0] = servletinputstream.readLine(abyte0, 0, abyte0.length);
if(ai[0] == -1)
return null;
break MISSING_BLOCK_LABEL_27;
Object obj;
obj;
return null;
if(s == null)
return new String(abyte0, 0, ai[0]);
return new String(abyte0, 0, ai[0], s);
obj;
return null;
}

}


JSP页:

<%@page contentType="text/html;charset=gb2312" import="package.upload"%>
<%
String Dir = "c:\dir\upload";
String fn="";
upload upload = new upload();
upload.setUploadDirectory(Dir);
fn=upload.uploadFile(request);
%>
随机图片名称
<%
mySmartUpload.initialize(pageContext);
mySmartUpload.service(request,response);
mySmartUpload.upload();
String fn=mySmartUpload.getFiles().getFile(0).getFileName();
mySmartUpload.save("upload/"); //文件保存的目录为upload
out.println("已经成功上传了文件,请查看<a href=upload/"+fn+">这里</a>");
%>
上面的程序可以上传图片,不过只能上传gif或者JPG图片。
而且保存图片在upload文件夹下面,要想GIF或Jpg图片的名称变为年+月+日+随机数.gif或年+月+日+随机数.jpg
只允许上传jpg或gif图片,在客户端用javaScript控制要好些。
变图片名称可用如下代码:自己看看就明白了。:
//得到实际路径

String realPath = this.masRequest.getRequest().getRealPath("/");
String userPhotoPath = realPath + "images\\UserPhoto\\";
userPhotoPath = MasString.replace(userPhotoPath,"\\","\\\\");
if (!file.getFileName().trim().equals(""))
{
//根据系统时间生成文件名
Date nowTime = new Date();
emp_Photo = userPhotoPath + String.valueOf(nowTime.getTime()) +"."+ file.getFileExt();
file.saveAs(emp_Photo);
System.out.println("file.saveAs() = " + "OK!!!");
}