文件上傳:java
項目中常常用到文件上傳。apache
本身實現文件上傳,使用文件上傳組件fileupload組件eclipse
一、指定表單類型爲文件上傳,jsp
enctype=」multipart/form-data」post
二、提交方式必須是:postspa
三、表單中存在文件域元素。code
須要的jar包orm
index.jsp對象
<body> <form action="${pageContext.request.contextPath}/FileUploadTest" method = "post" enctype="multipart/form-data"> 用戶名::<input type = "text" name = "username"/><br> 文件:<input type = "file" name = "file1"/><br> <input type = "submit"> </form> </body>
FileUploadTest.servlet
package zck.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class FileUploadTest */ @WebServlet("/FileUploadTest") public class FileUploadTest extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileUploadTest() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //建立文件上傳工廠類 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); //建立文件上傳核心類 ServletFileUpload upload = new ServletFileUpload(fileItemFactory); upload.setFileSizeMax(30*1024*1024);//設置單個文件最大值30M upload.setSizeMax(50*1024*1024);//最多50個文件 //判斷表單是不是文件上傳表單 if(upload.isMultipartContent(request)) { //把請求數據轉化爲FileItem對象集合 try { List<FileItem> list = upload.parseRequest(request); //遍歷獲得每個數據項 for(FileItem fileItem :list) { //判斷普通項,仍是文件。 if(fileItem.isFormField()) { //普通表單項 String fieldName =fileItem.getFieldName();//表單元素名稱 String content =fileItem.getString();//值 System.out.print(fieldName+"\n"+content+"\n\n"); }else { //文件上傳表單項 String name =fileItem.getName();//獲取文件名 //上傳文件目錄路徑 String basePath = ("D:\\software\\eclipse\\workplace2019-1\\UploadFiles\\WebContent\\upload\\"); //新建文件 File file = new File(basePath,name); fileItem.write(file); fileItem.delete();//刪除臨時文件 } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { System.out.print("不是文件上傳表單,不處理"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
運行界面blog
代碼中主要對象及屬性