SpringBoot文件夾上傳解決方案

前言:因本身負責的項目(jetty內嵌啓動的SpringMvc)中須要實現文件上傳,而本身對java文件上傳這一塊未接觸過,且對 Http 協議較模糊,故此次採用漸進的方式來學習文件上傳的原理與實踐。該博客重在實踐。html

 

一. Http協議原理簡介 java

    HTTP是一個屬於應用層的面向對象的協議,因爲其簡捷、快速的方式,適用於分佈式超媒體信息系統。它於1990年提出,通過幾年的使用與發展,獲得不斷地完善和擴展。目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的規範化工做正在進行之中,並且HTTP-NG(Next Generation of HTTP)的建議已經提出。web

    簡單來講,就是一個基於應用層的通訊規範:雙方要進行通訊,你們都要遵照一個規範,這個規範就是HTTP協議。面試

 1.特色:spring

  (1)支持客戶/服務器模式。數據庫

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

  (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頁面 

(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;

    @Override

    protected 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不能啓動,但權衡之下仍是應該設爲False

        connector.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)運行效果

上傳包含1W個文件的文件夾,正常

 

大型文件續傳功能正常 。

 

文件批量上傳正常

 

服務器中已經根據日期+GUID生成了目錄

數據庫中也有記錄

後端代碼邏輯大部分是相同的,目前可以支持MySQL,Oracle,SQL。在使用前須要配置一下數據庫,能夠參考我寫的這篇文章:http://blog.ncmem.com/wordpress/2019/08/12/java-http%E5%A4%A7%E6%96%87%E4%BB%B6%E6%96%AD%E7%82%B9%E7%BB%AD%E4%BC%A0%E4%B8%8A%E4%BC%A0/

歡迎入羣一塊兒討論:374992201

相關文章
相關標籤/搜索