创建Web项目SmartUpload
在WEB-INF目录里创建lib子目录,加入jspSmartUpload.jar
在web目录里创建上传子目录upload,用于存放上传文件
在web目录修改首页文件index.html
在web目录创建上传页面upload.html
在web目录里创建处理上传的页面do_upload.jsp
<%@ page import="com.jspsmart.upload.SmartUpload" %>
<%@ page import="com.jspsmart.upload.File" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%!
// 声明文件名及扩展名
String filename, ext;
%>
<%// 实例化上传组件SmartUpload su = new SmartUpload();// 初始化上传su.initialize(pageContext);// 定义上传文件的最大尺寸(单位:字节)long FILE_MAX_SIZE = 400000;// 判断上传文件类型是否符合要求try {// 设置上传文件类型su.setAllowedFilesList("jpg,gif,png,bmp");// 上传文件su.upload();} catch (Exception e) {out.print("<script type='text/javascript'>" +" alert('只能上传jpg, gif, png或bmp文件!');" +" window.location = 'upload.html';" +"</script>");}// 获取上传的第一个文件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 = filename + String.valueOf(System.currentTimeMillis()) + String.valueOf((int) (900 * Math.random()) + 100);// 获取应用程序的真实路径(物理路径)String realPath = application.getRealPath("/");// 构建上传文件的urlString url = realPath + "upload\\" + filename + "." + ext;// 将上传文件保存到指定的位置file.saveAs(url, SmartUpload.SAVE_PHYSICAL);// 提示用户上传成功out.print("文件上传成功!<br/>");out.print("保存位置:" + url + "<br/>");} else {out.print("<script type='text/javascript'>" +" alert('上传文件太大,上传失败!');" +" window.location = 'upload.html';" +"</script>");}}// 获取表单提交的姓名数据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>
重启服务器,显示运行结果
在web目录里创建下载页面download.html
在web目录里创建处理下载页面do_download.jsp
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.BufferedOutputStream" %>
<%@ page import="java.io.BufferedInputStream" %><%// 获取下载文件名String filename = request.getParameter("filename");// 获取下载文件路径String filePath = application.getRealPath("/upload/" + filename);boolean isInline = false; // 不允许浏览器直接打开// 清空缓冲区, 防止页面的空行, 空格添加到要下载的文件内容中去// 如果不清空的话在调用 response.reset() 的时候Tomcat会报错out.clear();try {File file = new File(filePath);if (file.exists() && file.canRead()) { // 文件存在且可读// 从服务器的配置来读取文件的 contentType 并设置此contentType, 不推荐设置为// application/x-download, 因为有时候我们的客户可能会希望在浏览器里直接打开,// 如 Excel 报表, 而且 application/x-download 也不是一个标准的 mime type,// 似乎 FireFox 就不认识这种格式的 mime type/*MIME类型就是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。 */String mimetype = null;mimetype = application.getMimeType(filePath);if (mimetype == null) {mimetype = "application/octet-stream;charset=ISO-8859-1";}response.setContentType(mimetype);// IE 的话就只能用 IE 才认识的头才能下载 HTML 文件, 否则 IE 必定要打开此文件!String ua = request.getHeader("User-Agent");// 获取客户端浏览器类型if (ua == null) {ua = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;)";}boolean isIE = ua.toLowerCase().indexOf("msie") != -1;// 判断用的是否为IE浏览器if (isIE && !isInline) { //用户采用的是IE浏览器而且不允许浏览器直接打开mimetype = "application/x-msdownload";}// 让客户端保存文件时显示正确文件名, 需要将文件名转换为 ISO-8859-1 编码String downFileName = new String(file.getName().getBytes(),"ISO-8859-1");String inlineType = isInline ? "inline" : "attachment";// 是否内联附件// or using this, but this header might not supported by FireFox//response.setContentType("application/x-download");response.setHeader("Content-Disposition", inlineType+ ";filename=\"" + downFileName + "\"");// 设置下载内容大小response.setContentLength((int) file.length());// 创建缓冲区byte[] buffer = new byte[4096];BufferedOutputStream output = null;BufferedInputStream input = null;try {output = new BufferedOutputStream(response.getOutputStream());// 源文件:输入流input = new BufferedInputStream(new FileInputStream(file));int n = -1;while ((n = input.read(buffer, 0, 4096)) != -1) {output.write(buffer, 0, n);}response.flushBuffer();} catch (Exception e) {out.write(e.toString());} // 用户可能取消了下载finally {if (input != null)input.close();if (output != null)output.close();}} else {out.println("文件不存在或不允许访问!");}} catch (Exception ex) {out.println(ex.toString());}
%>
重启服务器,查看下载文件运行效果