将jspSmartUpload.jar置于WEB-INF/lib下
下载
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 初始化
su.initialize(pageContext);
// 设定contentDisposition为null以禁止浏览器自动打开文件,
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
//doc时,浏览器将自动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
su.setContentDisposition(null);
// 下载文件
su.downloadFile("/upload/test.doc");
应用实例:
uploadimage.jsp
<%@ page contentType="text/html;charset=gb2312" language="java" import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%>
<%
SmartUpload mySmartUpload =new SmartUpload();
long file_size_max=4000000;
String fileName2="",ext="",testvar="";
String url="Admin/upload/"; //应保证在根目录中有此目录的存在
//初始化
mySmartUpload.initialize(pageContext);
//只允许上载此类文件
try {
mySmartUpload.setAllowedFilesList("jpg,gif");
//上载文件
mySmartUpload.upload();
} catch (Exception e){
%>
<SCRIPT language=#>
alert("只允许上传.jpg和.gif类型图片文件");
window.location='upload.htm';
</script>
<%
}
try{
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){%>
<SCRIPT language=#>
alert("请先选择要上传的文件");
window.location='upload.htm';
</script>
<%}
else{
//String myFileName=myFile.getFileName(); //取得上载的文件的文件名
ext= myFile.getFileExt(); //取得后缀名
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_size<file_size_max){
//更改文件名,取得当前上传时间的毫秒数值
Calendar calendar = Calendar.getInstance();
String filename = String.valueOf(calendar.getTimeInMillis());
saveurl=application.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路径
myFile.saveAs(saveurl,SmartUpload.SAVE_PHYSICAL);
out.print(saveurl);
String ret = "parent.HtmlEdit.focus();";
ret += "var range = parent.HtmlEdit.document.selection.createRange();" ;
ret += "range.pasteHTML('<img src=/"" + request.getContextPath() + "/admin/upload/" + filename + "." + ext + "/">');" ;
ret += "alert('上传成功!');";
ret += "window.location='upload.htm';";
out.print("<script language=#>" + ret + "</script>");
}
}
}catch (Exception e){
out.print(e.toString());
}
%>
upload.htm
<html>
<head>
<title>请选择上传的图片</title>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="45" align="center" valign="middle"><form action="uploadimage.jsp" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="上传">
</form></td>
</tr>
</table>
</body>
</html>
附将jspSmartUpload.jar下载:http://download.csdn.net/source/232392