1、创建Web项目SmartUploadDemo
2、在WEB-INF目录里创建lib子目录,加入jspSmartUpload.jar
3、在web目录里创建上传子目录upload,用于存放上传文件
在upload里存放一个图片文件scenery.jpg,后面用于测试下载功能。
4、在web目录修改首页文件index.html
5、在web目录创建上传页面upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>利用SmartUpload组件上传文件</title>
</head>
<body>
<form action="do_upload.jsp" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="name">
照片:<input type="file" name="photo">
<input type="submit" value="上传" onclick="return checkForm();">
</form>
<script type="text/javascript">
function checkForm() {
var filePhoto = document.getElementById("photo");
var photo=filePhoto.value;
if(photo ==""){
alert("注意,不能为空");
filePhoto.focus();
return false;
}
return true;
}
</script>
</body>
</html>
6、在web目录里创建处理上传的页面do_upload.jsp
<%--
Created by IntelliJ IDEA.
User: 邓益春
Date: 2019/11/18
Time: 8:31
To change this template use File | Settings | File Templates.
--%>
<%@ page import="com.jspsmart.upload.SmartUpload" %>
<%@ page import="com.jspsmart.upload.File" %>
<%@ page import="com.jspsmart.upload.SmartUploadException" %>
<%@ page import="java.io.IOException" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>利用SmartUpload组件上传文件</title>
</head>
<body>
<%!
String filename, ext;
%>
<%
//实例化上传组件
SmartUpload su = new SmartUpload();
//初始化上传
su.initialize(pageContext);
//定义上传文件最大尺寸(单位:字节)
long FILE_MAX_SIZE = 400000;
//判断上传文件类型是否符合要求
try {
//设置上传文件类型
su.setAllowedFilesList("jsp,gif,png,bmp");
//上传文件
su.upload();
} catch (SmartUploadException e) {
out.print("<script type='text/javascript'>"+
" alert('只能上传jpg,gif,png或bmp文件!');"+
" window.location = 'upload.html';"+
" </script>");
}
try {
File file = su.getFiles().getFile(0);
//判断是否获取文件
if (file.isMissing()){
out.print("<script type='text/javascript'>" +
" alert('上传文件失败,请再次选择文件上传!');" +
" window.location = 'upload.html';" +
"</script>");
}else {
if(file.getSize() < FILE_MAX_SIZE){
filename = file.getFieldName();//获得上传文件的文件名吗
ext = file.getFileExt();//获得上传文件的扩展名
//利用时间戳来修改文件名
filename = String.valueOf(System.currentTimeMillis())
+ String.valueOf((int) (900*Math.random())+ 100);
String realPath = application.getRealPath("/");
String url = realPath + "upload\\" + filename + "." + ext;
file.saveAs(url, SmartUpload.SAVE_PHYSICAL);
out.println("文件上传成功!" + "<br/>");
out.println("保存位置:" + url + "<br/>");
} else {
out.print("<script type='text/javascript'>" +
" alert('文件太大,上传失败!');" +
" window.location = 'upload.html';" +
"</script>");
}
}
} catch (IOException e) {
out.println(e.toString());
}
String name = su.getRequest().getParameter("name");
name = new String(name.getBytes(),"UTF-8");
%>
姓名:<%= name%><br/>
照片:<br/>
<img src="upload/<%= filename%>.<%= ext%>" width="300" height="250">
</body>
</html>