JSP中实现文件上传下载
文章目录
前言
在java web开发中,实现单个或多个文件的上传下载,可以借助jspsmartupload.jar包,这是一个可免费使用的文件上传下载组件(感谢开发者的无私奉献),也可以使用apache FileUpload组件。
这里以jspsmartupload组件为例说明。该jar包是一个基于JSP的文件上传与下载组件,可控性强,可以限制上传文件的扩展名、大小等,使用File类获取文件名、文件大小、扩展名等上传文件信息,还可同时实现文件下载功能。
一、文件上传
1、将jar包放入WEB-INF目录下的lib目录
将附件中的lib下载解压,放入java web工程目录下WEB-INF目录下的lib目录中,这里通常存放工程需要用到的jar包。
2、实现upload.jsp
<form action="MyUploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="fileName" multiple="multiple"> <br/> <br/>
<input type="submit" name ="upload" value="上传"><br/><br/>
<div id="Results"><%=(String)request.getAttribute("execResult") %></div>
</form>
3、实现MyUploadServlet
在servlet的doGet()中:
SmartUpload upload = new SmartUpload();//创建组件对象
upload.initialize(this.getServletConfig(), request, response);// 初始化
upload.setMaxFileSize(2 * 1024 * 1024);// 每个文件最大2M
upload.setTotalMaxFileSize(10 * 1024 * 1024);// 总共最大10M
upload.setAllowedFilesList("jpg,png");// 允许上传jpg,png
try {
upload.upload();
Files uploadFiles = upload.getFiles();
String filenameString = "";
//upload multiple files
for (int i = 0; i < uploadFiles.getCount(); i++) {
filenameString = uploadFiles.getFile(i).getFileName();
uploadFiles.getFile(i).saveAs("/upload/"+filenameString, File.SAVEAS_PHYSICAL);
//SAVEAS_PHYSICAL表明以操作系统的根目录为文件根目录另存文件,即:d:upload
//SAVEAS_VIRTUAL表明以Web应用程序的根目录为文件根目录另存文件,即:MyFileDraw下upload
}
//upload one file
/*String fileName = uploadFiles.getFile(0).getFileName();
* uploadFiles.getFile(0).saveAs("/upload/"+fileName,File.SAVEAS_PHYSICAL);
*
* */
request.setAttribute("execResult", "成功上传数量: " + uploadFiles.getCount());
System.out.println("成功上传数量: " + uploadFiles.getCount());
}
catch (SecurityException e) {
// TODO: handle exception
request.setAttribute("execResult", "文件只能是jpg/png,并小于2M!");
e.printStackTrace();
}
catch (SmartUploadException e) {
request.setAttribute("execResult", "文件只能是jpg/png,并小于2M!");
e.printStackTrace();
}
request.getRequestDispatcher("upload.jsp").forward(request, response);//将execResult回显
二、文件下载
1.download.jsp
代码如下:
<a href="MyDownloadServlet">下载文件</a>
2.MyDownloadServlet
代码如下:
response.setContentType("text/html; charset=UTF-8");
SmartUpload download = new SmartUpload();
download.initialize(this.getServletConfig(), request, response);// 初始化
download.setContentDisposition(null);
try {
download.downloadFile("/upload/java.docx");//下载的文件名
} catch (SmartUploadException e) {
response.getWriter().println("SmartUpload错误!");
e.printStackTrace();
}
catch (IOException e) {
response.getWriter().append("IOException错误:/upload/java.docx文件不存在");
e.printStackTrace();
}
catch (ServletException e) {
response.getWriter().println("ServletException错误!");
e.printStackTrace();
}