標籤:
需要兩個jar包
commons-fileupload-1.2.2.jar與commons-io-2.4.jar
表單格式必須為
<form action="fileupload.jsp" method="post" enctype="multipart/form-data">
一個接受檔案的例子
<%@page import="java.io.File"%><%@page import="org.apache.commons.fileupload.FileItem"%><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@ 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>My JSP ‘fileupload.jsp‘ starting page</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> <% request.setCharacterEncoding("utf-8"); String uploadpath="d:/upload"; //File folder=new File("upload"); DiskFileItemFactory factory= new DiskFileItemFactory(); factory.setSizeThreshold(30*1024); factory.setRepository(factory.getRepository()); ServletFileUpload upload=new ServletFileUpload(factory); int maxsize=5*1024*1024; List list=upload.parseRequest(request); Iterator iterator=list.iterator(); while(iterator.hasNext()){ FileItem item=(FileItem)iterator.next(); if(!item.isFormField()){ String filePath=item.getName(); if(filePath!=null){ File filename=new File(item.getName()); } if(item.getSize()>maxsize){ out.print("檔案太大 ,不得超過5M"); break; } File saveFile=new File(uploadpath,filePath); item.write(saveFile); out.print("檔案上傳成功 "); } response.sendRedirect("success.jsp"); } %> </body></html>
禁止上傳指定類型檔案:
<%@page import="org.apache.commons.io.filefilter.SuffixFileFilter"%><%@page import="java.io.File"%><%@page import="org.apache.commons.fileupload.FileItem"%><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%><%@ 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>My JSP ‘fileupload.jsp‘ starting page</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> <% request.setCharacterEncoding("utf-8"); String uploadpath="d:/upload"; //File folder=new File("upload"); DiskFileItemFactory factory= new DiskFileItemFactory(); factory.setSizeThreshold(30*1024); factory.setRepository(factory.getRepository()); ServletFileUpload upload=new ServletFileUpload(factory); int maxsize=5*1024*1024; List list=upload.parseRequest(request); String[] limit = new String[]{".exe", "dat"}; SuffixFileFilter filter = new SuffixFileFilter(limit); Iterator iterator=list.iterator(); while(iterator.hasNext()){ FileItem item=(FileItem)iterator.next(); if(!item.isFormField()){ String filePath=item.getName(); if(filePath!=null){ File filename=new File(item.getName()); } if(item.getSize()>maxsize){ out.print("檔案太大 ,不得超過5M"); break; } File saveFile=new File(uploadpath,filePath); boolean flag = filter.accept(saveFile); if(flag){ out.print("error"); break; }else{ item.write(saveFile); out.print("檔案上傳成功 "); }; } response.sendRedirect("success.jsp"); } %> </body></html>
對於form表單的屬性enctype,通常使用預設值application/x-www-form-urlencoded,這樣可以通過request對象的getParameter()方法擷取表單元素值,但是在檔案域中將表單的enctype屬性設定成了multipart/form-data,這樣通過getParameter()方法就無法擷取了。
下面介紹一個執行個體
上傳頁面
<% Date now = new Date(); String time = String.format("%tF", now); %> <form action="fileupload.jsp" method="post" enctype="multipart/form-data"> 選擇文檔<input type="file" name="file1" size="20"> 上傳者<input type="text" name="name" size="20"> 文檔名稱<input type="text" name="filenames" size="20"> 上傳時間<input type="text" name="upTime" value="<%=time %>"> <input type="submit" value="提交"/> </form>
處理頁面
<% String name=null, filenames=null, upTime=null,meg=null; request.setCharacterEncoding("utf-8"); String uploadpath = "d:/upload"; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(30*1024); factory.setRepository(factory.getRepository()); ServletFileUpload upload = new ServletFileUpload(factory); int maxsize = 5*1024*1024; List list = upload.parseRequest(request); Iterator iterator = list.iterator(); while(iterator.hasNext()){ FileItem item = (FileItem) iterator.next(); if(!item.isFormField()){ String filePath = item.getName(); if(filePath!=null){ File filename = new File(item.getName()); } if(item.getSize()>maxsize){ meg="too big"; break; } File saveFile = new File(uploadpath, filePath); item.write(saveFile); meg="success"; }else{ String formName = item.getFieldName(); String formcon = item.getString("utf-8"); if(formName.equals("name")){ name = formcon; } else if(formName.equals("filenames")){ filenames = formcon; } else if(formName.equals("upTime")){ upTime = formcon; } } } request.setAttribute("meg", meg); request.setAttribute("name", name); request.setAttribute("filenames", filenames); request.setAttribute("uptime", upTime); request.getRequestDispatcher("success.jsp").forward(request, response); %>
成功頁面
<body> ${requestScope.meg } ${requestScope.name } ${requestScope.filenames } ${requestScope.uptime } </body>
java上傳檔案