很多同学在使用jsp实现文件上传到服务器或者从服务器上下载文件到本地计算机这方面不是很了解,今天在这里我会帮助大家慢慢的实现这一功能。
准备工作:
1. 到网上下载两个包
第一个叫做commons-fileupload-1.2.1.jar
第二个叫做commons-io-1.3.2.jar
2. 建一个项目用来实现文件上传和下载
我创建的Web项目名为fileUpload,截图如下
3. 我们把从网上下载下来的包copy到WebRoot目录下Web-INF下的子目录lib目录里
然后打开Referenced Libraries,你会看见两个包已经存在于里面了。
下面我们开始实现文件上传
1. 首先我们创建一个名为uploadFile.jsp的页面,如下图:
点击浏览,可以出现以下画面
源代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+
":" +request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>实现文件上传到服务器</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="doFileUpload.jsp" method="post" enctype="multipart/form-data">
文件:<input type="file" name="chooseFile"/></br>
姓名:<input type="text" name="userName"/></br>
<input type="submit" value="提交">
</form>
</body>
</html>
注意:form表单里的enctype=”multipart/form-data”这一属性一定要写,这是用来标明此表单的类型是文件类型的。
2. 创建另一个jsp页面用来处理文件上传页面(实现功能),名为doFileUpload.jsp。一定要和form表单里action的值相同才行
源代码和注释如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.io.File"%>
<%
//先判断是否是文件上传类型enctype="multipart/form-data"
boolean isFileUpload = ServletFileUpload.isMultipartContent(request);
//如果是文件上传类型
if(isFileUpload){
//得到文件上传工厂
FileItemFactory factory = new DiskFileItemFactory();
//处理文件上传核心类
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//设置文件上传类的编码格式
fileUpload.setHeaderEncoding("UTF-8");
// 集合数据 : FileItem对象 注意: 每一个表单域 对应一个 FileItem对象(封装)
List<FileItem> fileItemList = fileUpload.parseRequest(request);
//遍历fileItemList
for(FileItem item: fileItemList){
//如果这个文本域是文件类型的
if(!item.isFormField()){
//得到文本域的value值,即 路径+文件名
String value = item.getName();
//得到文件名
String fileName = value.substring(value.lastIndexOf("\\")+1);
//得到上传的文件类型
//String fileType = fileName.substring(fileName.lastIndexOf("."));
//给文件重新命名 日期+文件名
fileName = new Date().getTime() + fileName;
//得到服务器的根路径
String rootPath = request.getRealPath("/");
//指定文件存放路径
String realPath = rootPath+"/"+"upload";
//定义文件存放的目录,注意 目录也是文件
File file = new File(realPath);
//如果目录不存在
if(!file.isDirectory()){
//创建文件上传目录
file.mkdirs();
}
File newFile = new File(realPath+"/"+fileName);
//向newFile文件中写入数据
item.write(newFile);
}else {//如果不是文件上传的文本域,把输入的内容显示在页面上
out.print("name=" + new String(
item.getFieldName().getBytes("ISO-8859-1"),"utf-8")
+",value="+ new String(
item.getString().getBytes("ISO-8859-1"),"utf-8"));
}
}
}
%>
OK,大功告成了!把项目发布到tomocat里,然后启动tomocat即可访问了,上传的文件的目录在tomocat的安装目录下此项目的根目录下例如D:\software\Tomcat 6.0\webapps\fileUpload,看看文件是不是已经在你创建的文件夹下了!
文件下载
创建download.jsp文件,源代码如下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileInputStream"%>
<%@pageimport="com.sun.xml.internal.messaging.saaj.util.ByteOutputStream"%>
<%@page import="java.io.OutputStream"%>
<%@page import="com.yinhe.entity.Users"%>
<%
//得到你要下载的文件名(由前一个页面传过来)
String fileName = new String
(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
//得到项目在tomcat 中的更路径
String realPath = request.getRealPath("/");
//得到文件在服务器中的路径
String path = realPath+ "upload/" + fileName;// 这就是文件所在完整路径
//清空response 所有信息
response.reset();
//设置IE浏览器内容类型 表示为 下载
response.setContentType("application/x-download;charset=UTF-8");
//设置IE浏览器的 头
response.setHeader("Content-Disposition","attachment;filename="+ fileName);
//从服务器上 读取文件
File file=new File(path); response.setContentLength(Integer.valueOf(((Long)file.length()).toString()));
//输入流 读取目标文件
FileInputStream fis=new FileInputStream(file);
int len=-1;
byte[] data=new byte[1024];
ByteOutputStream bos=new ByteOutputStream(1024);
// 文件读到最末尾 返回 -1
while((len=fis.read(data))!=-1)
{
//将服务器中的数据 转换成二进制数组 放入内存中
bos.write(data,0,len);
}
//将 服务器上的文件转换成 二进制数组 OutPutStream 输出流 写入对应文件中
OutputStream os= response.getOutputStream();
//从服务器 拿到数据 向客户端进行写入
os.write(bos.getBytes());
//清空内存文件 向客户端写入
os.flush();
//关闭输出流
os.close();
//关闭输入流
fis.close();
%>