檔案上傳的三種方式-Java

來源:互聯網
上載者:User

標籤:java   http協議   檔案上傳   jetty   

前言:因自己負責的項目(jetty內嵌啟動的SpringMvc)中需要實現檔案上傳,而自己對java檔案上傳這一塊未接觸過,且對 Http 協議較模糊,故這次採用漸進的方式來學習檔案上傳的原理與實踐。該部落格重在實踐。


一.Http協議原理簡介

    HTTP是一個屬於應用程式層的物件導向的協議,由於其簡捷、快速的方式,適用於分布式超媒體資訊系統。它於1990年提出,經過幾年的使用與發展,得到不斷地完善和擴充。目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的正常化工作進行中之中,而且HTTP-NG(Next Generation of HTTP)的建議已經提出。

    簡單來說,就是一個基於應用程式層的通訊規範:雙方要進行通訊,大家都要遵守一個規範,這個規範就是HTTP協議。

 1.特點:

  (1)支援客戶/伺服器模式。

  (2)簡單快速:客戶向伺服器請求服務時,只需傳送要求方法和路徑。要求方法常用的有GET、HEAD、POST。每種方法規定了客戶與伺服器聯絡的類型不同。由於HTTP協議簡單,使得HTTP伺服器的程式規模小,因而通訊速度很快。

  (3)靈活:HTTP允許傳輸任意類型的資料對象。正在傳輸的類型由Content-Type加以標記。

  (4)無串連:不需連線的含義是限制每次串連只處理一個請求。伺服器處理完客戶的請求,並收到客戶的應答後,即中斷連線。採用這種方式可以節省傳輸時間。

  (5)無狀態:HTTP協議是無狀態協議。無狀態是指協議對於交易處理沒有記憶能力。缺少狀態意味著如果後續處理需要前面的資訊,則它必須重傳,這樣可能導致每次串連傳送的資料量增大。另一方面,在伺服器不需要先前資訊時它的應答就較快。

  注意:其中(4)(5)是面試中常用的面試題。雖然HTTP協議(應用程式層)是無串連,無狀態的,但其所依賴的TCP協議(傳輸層)卻是常串連、有狀態的,而TCP協議(傳輸層)又依賴於IP協議(網路層)。


2.HTTP訊息的結構

 (1)Request 訊息分為3部分,第一部分叫請求行, 第二部分叫http header訊息頭, 第三部分是body本文,header和body之間有個空行, 結構如


 (2)Response訊息的結構, 和Request訊息的結構基本一樣。 同樣也分為三部分,第一部分叫request line狀態行, 第二部分叫request header訊息體,第三部分是body本文, header和body之間也有個空行,  結構如



下面是使用Fiddler捕捉請求baidu的Request訊息機構和Response訊息機構:


因為沒有輸入任何錶單資訊,故request的訊息本文為空白,大家可以找一個登入的頁面試試看。


  先到這裡,HTTP協議的知識網上很豐富,在這裡就不再熬述了。


二.檔案上傳的三種實現

1.Jsp/servlet 實現檔案上傳

 這是最常見也是最簡單的方式

 (1)實現檔案上傳的Jsp頁面

<html><head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><h2>File upload demo</h2><form action="fileload"  method="post" enctype="multipart/form-data">  <input type="file" name="filename" size="45"><br>  <input type="submit" name="submit" value="submit"></form></body></html>

 (2)負責接檔案的FileUploadServlet

import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;// @WebServlet(name = "FileLoadServlet", urlPatterns = {"/fileload"})public class FileLoadServlet extends HttpServlet {private static Logger logger = Logger.getLogger(FileLoadServlet.class);/** *  */private static final long serialVersionUID = 1302377908285976972L;@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {logger.info("------------ FileLoadServlet ------------");if (request.getContentLength() > 0) {           InputStream inputStream = null;           FileOutputStream outputStream = null;           try {inputStream = request.getInputStream();// 給新檔案拼上時間毫秒,防止重名long now = System.currentTimeMillis();File file = new File("c:/", "file-" + now + ".txt");file.createNewFile();outputStream = new FileOutputStream(file);byte temp[] = new byte[1024];int size = -1;while ((size = inputStream.read(temp)) != -1) { // 每次讀取1KB,直至讀完outputStream.write(temp, 0, size);}logger.info("File load success.");} catch (IOException e) {logger.warn("File load fail.", e);request.getRequestDispatcher("/fail.jsp").forward(request, response);} finally {outputStream.close();inputStream.close();}}request.getRequestDispatcher("/succ.jsp").forward(request, response);}}
 

  FileUploadServlet的配置,推薦採用servlet3.0註解的方式更方便

  <servlet>    <servlet-name>FileLoadServlet</servlet-name>    <servlet-class>com.juxinli.servlet.FileLoadServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>FileLoadServlet</servlet-name>    <url-pattern>/fileload</url-pattern>  </servlet-mapping>

 (3)運行效果

點擊"submit"



頁面轉向檔案上傳成功的頁面,再去C盤看看,發現多了一個檔案:file-1433417127748.txt,這個就是剛上傳的檔案



我們開啟看看,發現和原來的文本有些不一樣

             


結合前面講的HTTP協議的訊息結構,不難發現這些文本就是去掉"要求標頭"後的"Request訊息體"。所以,如果要得到與上傳檔案一致的文本,還需要一些字串操作,這些就留給大家了。

另外,大家可以試試一個Jsp頁面上傳多個檔案,會有不一樣的精彩哦o(∩_∩)o ,不解釋。


2.類比Post請求/servlet 實現檔案上傳

剛才我們是使用Jsp頁面來上傳檔案,假如用戶端不是webapp項目呢,顯然剛才的那種方式有些捉襟見襯了。

這裡我們換種思路,既然頁面上通過點擊可以實現檔案上傳,為何不能通過HttpClient來類比瀏覽器發送上傳檔案的請求呢。關於HttpClient ,大家可以自己去瞭解。

 (1)還是這個項目,啟動servlet服務


 (2)類比請求的FileLoadClient

import java.io.BufferedReader;import java.io.File;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.multipart.FilePart;import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;import org.apache.commons.httpclient.methods.multipart.Part;import org.apache.log4j.Logger;public class FileLoadClient {private static Logger logger = Logger.getLogger(FileLoadClient.class);public static String fileload(String url, File file) {String body = "{}";if (url == null || url.equals("")) {return "參數不合法";}if (!file.exists()) {return "要上傳的檔案名稱不存在";}PostMethod postMethod = new PostMethod(url);        try {                    // FilePart:用來上傳檔案的類,file即要上傳的檔案            FilePart fp = new FilePart("file", file);            Part[] parts = { fp };            // 對於MIME類型的請求,httpclient建議全用MulitPartRequestEntity進行封裝            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());            postMethod.setRequestEntity(mre);                        HttpClient client = new HttpClient();            // 由於要上傳的檔案可能比較大 , 因此在此設定最大的連線逾時時間            client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000);                        int status = client.executeMethod(postMethod);            if (status == HttpStatus.SC_OK) {                InputStream inputStream = postMethod.getResponseBodyAsStream();                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));                                StringBuffer stringBuffer = new StringBuffer();                String str = "";                while ((str = br.readLine()) != null) {                    stringBuffer.append(str);                }                                body = stringBuffer.toString();                            } else {            body = "fail";            }        } catch (Exception e) {            logger.warn("上傳檔案異常", e);        } finally {            // 釋放串連            postMethod.releaseConnection();        }return body;}public static void main(String[] args) throws Exception {String body = fileload("http://localhost:8080/jsp_upload-servlet/fileload", new File("C:/1111.txt"));System.out.println(body);}}


 (3)在Eclipse中運行FileLoadClient程式來發送請求,運行結果:

<html><head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><h2>File upload success</h2><a href="index.jsp">return</a></body></html>
列印了:檔案上傳成功的succ.jsp頁面




有沒有發現什麼,是不是和前面Jsp頁面上傳的結果類似?對的,還是去掉"要求標頭"後的"Request訊息體"。


這種方式也很簡單,負責接收檔案的FileUploadServlet沒有變,只要在用戶端把檔案讀取到流中,然後類比請求servlet就行了。


3.類比Post請求/Controller(SpringMvc)實現檔案上傳

終於到第三種方式了,主要痛點在於搭建maven+jetty+springmvc環境,接收檔案的service和類比請求的用戶端 和上面相似。


 (1)類比請求的FileLoadClient未變

import java.io.BufferedReader;import java.io.File;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.multipart.FilePart;import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;import org.apache.commons.httpclient.methods.multipart.Part;import org.apache.log4j.Logger;public class FileLoadClient {private static Logger logger = Logger.getLogger(FileLoadClient.class);public static String fileload(String url, File file) {String body = "{}";if (url == null || url.equals("")) {return "參數不合法";}if (!file.exists()) {return "要上傳的檔案名稱不存在";}PostMethod postMethod = new PostMethod(url);        try {                    // FilePart:用來上傳檔案的類,file即要上傳的檔案            FilePart fp = new FilePart("file", file);            Part[] parts = { fp };            // 對於MIME類型的請求,httpclient建議全用MulitPartRequestEntity進行封裝            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());            postMethod.setRequestEntity(mre);                        HttpClient client = new HttpClient();            // 由於要上傳的檔案可能比較大 , 因此在此設定最大的連線逾時時間            client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000);                        int status = client.executeMethod(postMethod);            if (status == HttpStatus.SC_OK) {                InputStream inputStream = postMethod.getResponseBodyAsStream();                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));                                StringBuffer stringBuffer = new StringBuffer();                String str = "";                while ((str = br.readLine()) != null) {                    stringBuffer.append(str);                }                                body = stringBuffer.toString();                            } else {            body = "fail";            }        } catch (Exception e) {            logger.warn("上傳檔案異常", e);        } finally {            // 釋放串連            postMethod.releaseConnection();        }return body;}public static void main(String[] args) throws Exception {String body = fileload("http://localhost:8080/fileupload/upload", new File("C:/1111.txt"));System.out.println(body);}

 (2)servlet換為springMvc中的Controller

import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping("/fileupload")public class FileUploadService {private Logger logger = Logger.getLogger(FileUploadService.class);@RequestMapping(consumes = "multipart/form-data", value = "/hello", method = RequestMethod.GET)public void hello(HttpServletRequest request, HttpServletResponse response) throws IOException {response.getWriter().write("Hello, jetty server start ok.");}@RequestMapping(consumes = "multipart/form-data", value = "/upload", method = RequestMethod.POST)public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {String result = "";if (request.getContentLength() > 0) {           InputStream inputStream = null;           FileOutputStream outputStream = null;           try {inputStream = request.getInputStream();// 給新檔案拼上時間毫秒,防止重名long now = System.currentTimeMillis();File file = new File("c:/", "file-" + now + ".txt");file.createNewFile();outputStream = new FileOutputStream(file);byte temp[] = new byte[1024];int size = -1;while ((size = inputStream.read(temp)) != -1) { // 每次讀取1KB,直至讀完outputStream.write(temp, 0, size);}logger.info("File load success.");result = "File load success.";} catch (IOException e) {logger.warn("File load fail.", e);result = "File load fail.";} finally {outputStream.close();inputStream.close();}}response.getWriter().write(result);}}

 (3)啟動jetty的核心代碼,在Eclipse裡面右鍵可以啟動,也可以把項目打成jar報啟動

import org.apache.log4j.Logger;import org.eclipse.jetty.server.Connector;import org.eclipse.jetty.server.Server;import org.eclipse.jetty.server.ServerConnector;import org.eclipse.jetty.webapp.WebAppContext;public class Launcher {private static Logger logger = Logger.getLogger(Launcher.class);private static final int PORT = 8080;private static final String WEBAPP = "src/main/webapp";private static final String CONTEXTPATH = "/";private static final String DESCRIPTOR = "src/main/webapp/WEB-INF/web.xml";/* * 建立 Jetty Server,指定其連接埠、web目錄、根目錄、web路徑 * @param port * @param webApp * @param contextPath * @param descriptor * @return Server */public static Server createServer(int port, String webApp, String contextPath, String descriptor) {Server server = new Server();//設定在JVM退出時關閉Jetty的鉤子//這樣就可以在整個功能測試時啟動一次Jetty,然後讓它在JVM退出時自動關閉server.setStopAtShutdown(true);ServerConnector connector = new ServerConnector(server); connector.setPort(port); //解決Windows下重複啟動Jetty不報告連接埠衝突的問題//在Windows下有個Windows + Sun的connector實現的問題,reuseAddress=true時重複啟動同一個連接埠的Jetty不會報錯//所以必須設為false,代價是若上次退出不乾淨(比如有TIME_WAIT),會導致新的Jetty不能啟動,但權衡之下還是應該設為Falseconnector.setReuseAddress(false);server.setConnectors(new Connector[]{connector});WebAppContext webContext = new WebAppContext(webApp, contextPath);webContext.setDescriptor(descriptor);// 設定webapp的位置webContext.setResourceBase(webApp);webContext.setClassLoader(Thread.currentThread().getContextClassLoader());server.setHandler(webContext);return server;}/** * 啟動jetty服務 *  */public void startJetty() {final Server server = Launcher.createServer(PORT, WEBAPP, CONTEXTPATH, DESCRIPTOR);try {server.start();server.join();} catch (Exception e) {logger.warn("啟動 jetty server 失敗", e);System.exit(-1);}}public static void main(String[] args) {(new Launcher()).startJetty();// jetty 啟動後的測試url// http://localhost:8080/fileupload/hello}}


springMvc的配置不貼了,大家可以下載源碼下來看。


 (4)運行效果

運行 Launcher 後可以訪問http://localhost:8080/fileupload/hello 查看jetty+springMvc啟動是否正常



運行 FileLoadClient後列印的日誌:



說明檔案上傳成功




附源碼下載:

jsp_upload-servlet項目:(1).Jsp/servlet 實現檔案上傳  (2).類比Post請求/servlet 實現檔案上傳

jetty_upload-springmvc項目:(3).類比Post請求/Controller(SpringMvc)實現檔案上傳

csdn

檔案上傳的三種方式-Java


GitHub

https://github.com/leonzm/jsp_upload-servlet.git
https://github.com/leonzm/jetty_upload-springmvc.git


時間比較倉促,可能有不對或者不完善的地方,大家可以提出來一起學習。


參考&引用:

淺析HTTP協議
http://www.cnblogs.com/gpcuster/archive/2009/05/25/1488749.html

HTTP協議詳解
http://blog.csdn.net/gueter/article/details/1524447

HTTP 協議詳解
http://kb.cnblogs.com/page/130970/

HttpClient學習整理
http://www.cnblogs.com/ITtangtang/p/3968093.html


TCP/IP、Http、Socket的區別
http://jingyan.baidu.com/article/08b6a591e07ecc14a80922f1.html


Spring MVC 教程,快速入門,深入分析
http://yinny.iteye.com/blog/1926799

jetty啟動以及嵌入式啟動
http://yinny.iteye.com/blog/1926799

啟動jetty方式
http://hbiao68.iteye.com/blog/2111007

Jetty較實用引導程式
http://www.xuebuyuan.com/1400368.html



檔案上傳的三種方式-Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.