这是一个已经封装好了的commons-io操作文件上传下载的工具类。使用只需要改变上传,下载的路径即可;
public class CommonsUtil {
private static final int MEMORY_THR = 1024*1024*3;
private static final int FILE_MAX = 1024*1024*200;
private static final int MAX = 1024*1024*1000;
private static final String UPLOAD_PATH = "upload";
//private static final ;
//--------------------上传文件---------------------------------------
public static Map<String, Object> upLoad(HttpServletRequest request){
//保存文件,同时接收表单中的其他信息;
//配置文件上传信息
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置内存临界值,超过范围,存入临时目录中;
factory.setSizeThreshold(MEMORY_THR);
//设置超出范围的临时目录;
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
//配置上传文件参数;
upload.setFileSizeMax(FILE_MAX);
upload.setSizeMax(MAX);
upload.setHeaderEncoding("utf-8");
//创建对象,接收表单其它数据;
HashMap<String, Object> map = new HashMap<String, Object>();
//拼接一下上传文件的保存路径;
String uppath = request.getServletContext().getRealPath("")+File.separator+UPLOAD_PATH;
//判断上传的是File,还是text;
//解析传过来的参数;
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while(it.hasNext()){
FileItem item = (FileItem) it.next();
if(item.isFormField()){
String value = item.getString("utf-8");
String name = item.getFieldName();
map.put(name, value);
// System.out.println("name==>"+name+"value==>"+value);
}else{
//操作文件
String type = item.getFieldName();
String filename = new File(item.getName()).getName();
String getname = item.getName();
//将上传的文件,文件名保存到数据库中:
// System.out.println("type==>"+type+"value==>"+filename+"getname==>"+getname);
map.put(type, filename);
//指定存放位置;
String savepath = uppath+"/"+filename;
File storfile = new File(savepath);
//将文件保存到服务器磁盘中
item.write(storfile);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//---------------------获取上传的所有文件----------------------------------------------------------
public static void display(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
//上传文件目录
String uploadPath = request.getServletContext().getRealPath("/upload");
//定义 集合 存放文件名称
/*Map<String, String> fileNameMap = new HashMap<String, String>();*/
List<String> list = new ArrayList<String>();
//根据路径生成 文件
File file = new File(uploadPath);
//调用方法
judgeFile(file, list);
request.setAttribute("comlist", list);
request.getRequestDispatcher("../downupload.jsp").forward(request, response);
}
//------------------递归遍历文件--------------------------------------
public static void judgeFile(File file,List list){
if(!file.isFile()){
File[] files= file.listFiles();
for (File f : files) {
judgeFile(f, list);
}
}else{
//map.put(file.getName(), file.getName());
list.add(file.getName());
}
}
//-----------------------下载文件------------------------------------------------
public static void downloadFile(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
//获取下载文件名称
String fileName = req.getParameter("filename");
fileName = new String(fileName.getBytes("iso-8859-1"),"utf-8");
//确定下载的目录文件夹
String fileSavePath = req.getServletContext().getRealPath("/upload");
//拼接下载的文件路径
File file = new File(fileSavePath+"\\"+fileName);
if(!file.exists()){
req.setAttribute("message", "下载的文件不存在....");
req.getRequestDispatcher("../downupload.jsp").forward(req, res);
return;
}
//如果文件存在 则下载
res.setHeader("content-disposition","attachment; filename="+URLEncoder.encode(fileName, "utf-8"));
//已文件流的方式 进行下载操作
FileInputStream in = new FileInputStream(file);
OutputStream out = res.getOutputStream();
byte buffer[] = new byte[1024];
int lne = 0;
//循环读取
while((lne=in.read(buffer))>0){
out.write(buffer, 0, lne);
}
in.close();
out.close();
}
}
servlet服务层只需要调用相对应的上传下载的方法即可:
public class CommonsFlie extends BaseServlet {
public void comupLoad(HttpServletRequest request, HttpServletResponse response) throws IOException{
CommonsUtil.upLoad(request);
response.sendRedirect("../downupload.jsp");
}
public void comdisplay(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
CommonsUtil.display(request, response);
}
public void comdownLoad(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
CommonsUtil.downloadFile(request, response);
}
前台页面发送请求:
<h3>commons-io-方式上传文件</h3>
<form method="POST" ENCTYPE="multipart/form-data" action="servlet/CommonsFlie?op=comupLoad">
<input type="file" name="upfile"/>
<span>昵称:</span> <input type="text" name="username"/>
<span>年龄:</span> <input type="text" name="userage"/>
<input type="submit" value="上传">
</form>
<a href="servlet/CommonsFlie?op=comdisplay">显示文件列表</a><br>
<c:forEach items="${comlist }" var="item">
<a href="servlet/CommonsFlie?op=comdownLoad&filename=${item }"> <span>下载:${item }</span></a><br>
</c:forEach>
本文介绍了一个使用commons-io库进行文件上传和下载操作的工具类。只需指定上传及下载路径,即可在服务层轻松调用相关方法完成文件交互。
5220





