文件的上传与下载案例
要求:
提供文件上传,上传大小有要求
有页面显示已上传列表
可以在上传列表中去下载文件
首先是jsp页面,一个是主页面,是否,有两个选择——上传和下载列表
代码如下:(index.jsp)
<body>
<a href="${pageContext.request.contextPath }/demo/upload.jsp">文件上传</a>
<a href="${pageContext.request.contextPath }/fileServlet?method=downList">文件下载</a>
</body>
然后是文件上传的页面
<%@ 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>upload.jsp</title>
</head>
<body>
<center>
<form action="${pageContext.request.contextPath }/fileServlet?method=upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="userName"/>
文件 :<input type="file" name="file_img"/>
<input type="submit" value="提交"/>
</form>
</center>
</body>
</html>
接着是文件的servlet处理(在服务器端我创建了一个文件夹(upload)用于存放上传文件)
package com.gqx.demoServlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class fileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取请求参数,区分是什么方法
String method=request.getParameter("method");
if ("upload".equals(method)) {
//上传
try {
upload(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ("downList".equals(method)) {
//下载
downList(request,response);
}
if ("down".equals(method)) {
try {
down(request,response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
//1、创建工厂类对象
DiskFileItemFactory factory=new DiskFileItemFactory();
//2、创建文件核心下载类
ServletFileUpload upload=new ServletFileUpload(factory);
//设置文件大小限制的参数
upload.setFileSizeMax(10*1024*1024); //设置单个文件的最大上传容量
upload.setSizeMax(50*1024*1024); //设置总文件的最大上传容量
upload.setHeaderEncoding("utf-8"); //对中文文件进行编码处理
//判断是否是表单提交项
if (upload.isMultipartContent(request)) {
//3、把请求数据转化为List集合
List<FileItem> list=upload.parseRequest(request);
//遍历
for (FileItem fileItem : list) {
//判断是否为普通文本数据
if (fileItem.isFormField()) {
//普通文本数据
String name=fileItem.getFieldName();
String value=fileItem.getString();
System.out.println(name+":"+value);
}else {
//文件上传
//获取文件名称
String name=fileItem.getName();
/***处理上传文件重命名问题**/
//a、先得到唯一的标记
String id=UUID.randomUUID().toString(); //生成一组唯一的字符串
//b、拼接文件名
name=id+"#"+name;
//得到文件上传目录
String basePath=getServletContext().getRealPath("/upload");
//创建文件的上传对象
File file =new File(basePath,name);
//开始上传
fileItem.write(file);
//删除组件运行的时候产生的临时文件
fileItem.delete();
}
}
}
response.sendRedirect(request.getServletContext().getContextPath()+"/demo/index.jsp");
}
private void downList(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/**实现思路:先获取upload目录下的所有文件的文件名,在保存,跳转到down.jsp列表展示*/
//1. 初始化map集合Map<包含唯一标记的文件名, 简短文件名> ;
Map<String,String> fileMap=new HashMap<String, String>();
//2、获取上传目录,及其所有文件的文件名
String basePath=getServletContext().getRealPath("/upload");
//目录
File file=new File(basePath);
//目录下所有文件名
String list[]=file.list();
//遍历
if (list!=null && list.length > 0) {
//解析服务器下的文件名
for (int i=0;i<list.length;i++) {
//全名
String fileName=list[i];
//短名
String shortName=fileName.substring(fileName.indexOf("#")+1);
//封装
fileMap.put(fileName, shortName);
}
}
//3、保存到request域fileNamess
request.setAttribute("fileNames", fileMap);
request.getRequestDispatcher("/demo/downList.jsp").forward(request, response);
}
/**
* 处理文件下载
* @param request
* @param response
*/
private void down(HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
//获取用户下载的文件名(url后面追加的,get请求)
String fileName=request.getParameter("fileName");
fileName=new String(fileName.getBytes("iso-8859-1"),"utf-8");
//先获取上传目录路径
String basePath=getServletContext().getRealPath("/upload");
//获取一个文件流
InputStream in=new FileInputStream(new File(basePath,fileName));
//如果文件名是中文,要进行url编码
fileName =URLEncoder.encode(fileName,"UTF-8");
// 设置下载的响应头
response.setHeader("content-disposition", "attachment;fileName=" + fileName);
//获取response字节流
OutputStream out=response.getOutputStream();
byte[] bytes=new byte[1024];
int len=-1;
while((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
}
out.close();
in.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
有了它,就可以得到文件的列表及下载页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'downList.jsp' starting page</title>
</head>
<body>
<table border="1" align="center">
<tr>
<th>序号</th>
<th>文件名</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.fileNames }" var="en" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${en.value }</td>
<td>
<!--
<a href="${pageContext.request.contextPath}/fileServlet/method=down&.....">文件下载</a>
这样写太麻烦了
-->
<!-- 可以构建一个地址,如下 -->
<c:url var="url" value="fileServlet"> <!-- 默认是当前的目录,如果要改到其他的项目,就写context="/another" -->
<c:param name="method" value="down"></c:param>
<c:param name="fileName" value="${en.key }"></c:param>
</c:url>
<!-- 使用上面的地址 -->
<a href="${url }">下载</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
效果如图
上传的列表与下载的文件


很希望自己是一棵树,守静、向光、安然,敏感的神经末梢,触着流云和微风,窃窃的欢喜。脚下踩着最卑贱的泥,很踏实。还有,每一天都在隐秘成长。

浙公网安备 33010602011771号