這裏我創建了一個maven工程,直接添加下載的依賴,爲何選擇maven?由於個人目的是爲了完成上傳,而不是爲了去配置環境~!在上傳的時候,必需要添加io這個依賴的包,若是我這裏用的是servlet,就須要添加對應的javax.servlet依賴,這是很重要的。另外,在表單提交的時候,enctype="multipart/form-data"是必需要填的,這個在w3c文檔裏有明確規定,而對於上傳的路徑、怎麼上傳等這些則是次要的,因此我沒有過多的去判斷有什麼類型的文件,也就是說,這裏我是爲了實現servlet上傳而實現上傳。 這是最基本的原理,不管你是spring mvc上傳仍是struts2,其實原理都是差很少的。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="uploadServlet" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="file" /><br> <input type="submit" value="提交" > </form> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Servlet Upload Web Application</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>uploadServlet</servlet-name> <servlet-class>com.iflytek.test.MyUploadServlet</servlet-class> <init-param> <param-name>fileName</param-name> <param-value>myUploadServlet</param-value> </init-param> <init-param> <param-name>cachePath</param-name> <param-value>cachePath</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>uploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
<?xml version="1.0" encoding="UTF-8"?> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>ServletUploadTrain</name> <groupId>com.iflytek.test</groupId> <artifactId>ServletUploadTrain</artifactId> <version>0.0.1-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.7</version> <configuration> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8888</port> <maxIdleTime>30000</maxIdleTime> </connector> </connectors> <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory> <contextPath>/</contextPath> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <!-- common-io包 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- fileupload上傳配置 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- serlvet配置 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> </project>
package com.iflytek.test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletConfig; 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.DiskFileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class MyUploadServlet extends HttpServlet { /** * 文件存放地址 */ private String file_path; /** * 緩存路徑 */ private File cacheFile; /* * (non-Javadoc) * * @see * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest * , javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } /* * (non-Javadoc) * * @see * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest * , javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //super.doPost(req, resp); // resp.setContentType("text/plain"); // 設置字符集 resp.setCharacterEncoding("GBK"); // PrintWriter printWriter = resp.getWriter(); // 建立一個基於硬盤的工廠,通常用來緩衝 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5*1024); //設置緩存文件 factory.setRepository(cacheFile); ServletFileUpload fileUpload = new ServletFileUpload(factory); // 頁面請求傳遞的信息量的最大值爲20M fileUpload.setSizeMax(20 * 1024 * 1204); // 設置單個文件傳遞的大小爲6m fileUpload.setFileSizeMax(6 * 1024 * 1024); try { List<FileItem> list = fileUpload.parseRequest(req); for (FileItem fileItem : list) { if (fileItem.isFormField()) { // 提交的是表單元素 this.processFormFileld(fileItem, printWriter); } else { this.processUploadFile(fileItem, printWriter); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 若是表單中的是文件信息格式,則將文件保存到指定的目錄下 * * @param fileItem * 文件信息 * @param printWriter * 輸出打印對象 */ private void processUploadFile(FileItem fileItem, PrintWriter printWriter) throws Exception { String filename = fileItem.getFieldName(); int index = filename.lastIndexOf("\\"); filename = filename.substring(index + 1, filename.length()); long file_size = fileItem.getSize(); if ("".equals(filename) && file_size == 0) { return; } File upload_file = new File(file_path + "/" + filename); // 系統會自動將臨時文件刪除 fileItem.write(upload_file); printWriter.println("<p>文件" + filename + "上傳成功!</p>"); printWriter.println("<p>文件[" + filename + "]的大小爲" + file_size + "</p>"); } /** * 若是表單的信息爲文本信息,則打印簡單的提示 * * @param fileItem * 文本信息 * @param printWriter * 輸出打印對象 */ private void processFormFileld(FileItem fileItem, PrintWriter printWriter) throws Exception { String name = fileItem.getFieldName(); String value = fileItem.getString(); printWriter.println("<p>" + name + ":" + value + "</p>"); } /* * (non-Javadoc) * * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); // 查詢要上傳文件所在的文件夾是否存在,如不存在就創建一個文件夾 String fileName = config.getInitParameter("fileName"); String cachePath = config.getInitParameter("cachePath"); // 經過虛擬的初始化參數來構建一個真實的文件路徑 file_path = this.getServletContext().getRealPath(fileName); cachePath = this.getServletContext().getRealPath(cachePath); File realFile = new File(file_path); cacheFile = new File(cachePath); if(!cacheFile.exists()){ cacheFile.mkdirs(); } if (!realFile.exists()) { // 創建一些列路徑 realFile.mkdirs(); } } }