一、文件上传
文件的上传也是基于表单来完成的,表单中的file元素可以自动生成一个文本框和一个按钮,文本框可以输入本地文件名或路径,点击按钮则可以打开一个文件选择框让用户选中本地文件。需要注意的是在文件上传时还必须设置表单的enctype属性,并将它的值设置为multipart/form-data。
upload.jsp
<FORM METHOD="POST" ENCTYPE="multipart/form-data"
ACTION="SmartUpladServlet.do">
<INPUT TYPE="text" name="userName"><br>
<INPUT TYPE="file" NAME="myFile"><br>
<INPUT TYPE="file" NAME="myFile2"><br>
<INPUT TYPE="file" NAME="myFile3"><br>
<INPUT TYPE="SUBMIT" value="上传">
</FORM>
</body>
采用的是SmartUpload,需要SmartUpload的包。
上传文件的Servlet
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class SmartUpladServlet extends HttpServlet {
public SmartUpladServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//文件上传个数
int count = 0;
//文件上传地址
String filePath = getServletContext().getRealPath("/")+"smartUpload";
//如果文件夹不存在 则创建这个文件夹
File file = new File(filePath);
if(!file.exists())
{
file.mkdir();
}
//初始化对象
SmartUpload su = new SmartUpload();
su.initialize(getServletConfig(),request,response);
//设置文件最大容量
su.setMaxFileSize(10*1024*1024);
//设置所有文件最大容量
su.setTotalMaxFileSize(100*1024*1024);
//设置上传文件类型
su.setAllowedFilesList("rar,txt,jpg,bmp,gif");
try {
//设置禁止上传的文件类型
su.setDeniedFilesList("jsp,js,html,css");
//上传文件
su.upload();
System.out.println("userName=" + su.getRequest().getParameter("userName"));
count = su.save(filePath);
}
catch (SQLException e) {
e.printStackTrace();
}
catch (SmartUploadException e) {
e.printStackTrace();
}
for (int i = 0; i < su.getFiles().getCount(); i++) {
com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
System.out.println("表单项名称:" + tempFile.getFieldName());
System.out.println("文件名:" + tempFile.getFileName());
System.out.println("文件长度:" + tempFile.getSize());
System.out.println("文件扩展名:" + tempFile.getFileExt());
System.out.println("文件全名:" + tempFile.getFilePathName());
}
System.out.println("上传成功!共" + count + "个文件!");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void init() throws ServletException {
}
}
web.XML文件配置
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>SmartUpladServlet</servlet-name>
<servlet-class>com.kay.servlet.SmartUpladServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SmartUpladServlet</servlet-name>
<url-pattern>/SmartUpladServlet.do</url-pattern>
</servlet-mapping>
二、文件下载
通过超链接下载文件,会暴露了下载文件在服务器中的真实地址,不利于对资源进行安全保护,而且利用超链接下载文件,服务器端得文件只能存放在Web应用程序所在的目录下。利用程序编码实现下载,可以增加安全机制,比如我们只能让VIP会员下载等等。还可以从任意位置进行下载,我们可以将文件放到Web应用程序外的目录中。
显示文件夹内所有文件的servlet
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = "c:/file";
//声明集合存放目录下所有文件的文件名
List<String> fileList = new ArrayList<String>();
File folder = new File(path);
//判断文件夹是否存在并且是否是一个目录
if(folder.exists() && folder.isDirectory()){
//获得目录中所有文件及目录
File[] files = folder.listFiles();
for (File file : files) {
//如果是文件
if(file.isFile()){
//将文件名放入集合中
fileList.add(file.getName());
}
}
}
request.setAttribute("fileList", fileList);
request.getRequestDispatcher("showfile.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
showfile.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>显示所有文件</title>
</head>
<body>
请选择您要下载的文件:<br/>
<c:forEach items="${fileList}" var="fileName">
<a href="downLoadServlet?filename=${fileName }">${fileName }</a><br/>
</c:forEach>
</body>
</html>
下载文件的DownLoadServlet
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownLoadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = "C:/file";
String fileName = request.getParameter("filename");
File file = new File(path + "/" + fileName);
//如果文件存在
if (file.exists()) {
//设置响应类型及响应头
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment; filename=\""
+ fileName + "\"");
//读取文件
InputStream inputStream = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(inputStream);
byte[] bytes = new byte[1024];
ServletOutputStream outStream = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(outStream);
int readLength = 0;
while ((readLength = bis.read(bytes)) != -1) {
bos.write(bytes, 0, readLength);
}
//释放资源
inputStream.close();
bis.close();
bos.flush();
outStream.close();
bos.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
原帖地址:http://blog.sina.com.cn/s/blog_60f823dd01017nz9.html