java檔案上傳-使用apache-fileupload組件

來源:互聯網
上載者:User

標籤:public   擷取   post   enc   group   http   記憶體   jsp   ima   

 目前檔案上傳的(架構)組件:Apache----fileupload 、Orialiy – COS – 2008() 、Jsp-smart-upload – 200M。用fileupload上傳檔案:

需要匯入第三方包:

       Apache-fileupload.jar – 檔案上傳核心包。

       Apache-commons-io.jar – 這個包是fileupload的依賴包。同時又是一個工具包。

使用springmvc,解決煩人的post亂碼問題,建立maven項目:

maven依賴:

<dependency>    <groupId>commons-fileupload</groupId>        <artifactId>commons-fileupload</artifactId>        <version>${commons-fileupload.version}</version></dependency><dependency>     <groupId>commons-io</groupId>     <artifactId>commons-io</artifactId>      <version>${commons-io.version}</version></dependency>
版本:

<commons-io.version>1.3.2</commons-io.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>

 

 

核心類:

       DiskFileItemFactory – 設定磁碟空間,儲存臨時檔案。只是一個具類。

       ServletFileUpload  - 檔案上傳的核心類,此類接收request,並解析reqeust

  ServletFileUpload.parseRequest(request);  --List<FileItem>   解析request

       一個FileItem就是一個標識分隔字元開始 到結束。如:

 

查看DiskFileItemFactory原始碼,可知

If not otherwise configured, the default configuration values are as follows:   Size threshold is 10KB.   Repository is the system default temp directory, as returned by   System.getProperty("java.io.tmpdir")

 可知,如果不設定臨時目錄,會儲存在預設的臨時目錄-  System.getProperty("java.io.tmpdir");這個目錄正是windows系統的臨時檔案存放目錄,通過環境變數,可找到這個目錄

這裡存放著許多臨時檔案。

 controller:
package com.lhy.upload.controller;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.util.List;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.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** *  * DiskFileItemFactory:設定磁碟空間,儲存臨時檔案,只是一個工具類。 * 構造器 DiskFileItemFactory(int sizeThreshold, File repository): *     sizeThreshold: *         設定緩衝儲存(記憶體)儲存多少位元組資料,預設10K。 *         如果一個檔案沒有大於10K,則直接使用記憶體,直接儲存成檔案就可以了。 *         如果一個檔案大於10K,就需要將檔案先儲存到臨時檔案中去。 *     repository: *         臨時目錄的位置。 *  *  * ServletFileUpload:檔案上傳核心類,接收request 並解析。 * */@RequestMapping("/upload")@Controllerpublic class UploadController {        @RequestMapping("uploadFile")    public void uploadFile(HttpServletRequest request,HttpServletResponse response){        //擷取tomcat下的up目錄的路徑           String path = request.getSession().getServletContext().getRealPath("/up");        //1,聲明DiskFileItemFactory工廠類,用於在指定磁碟上設定一個臨時目錄        DiskFileItemFactory disk = new DiskFileItemFactory(1024*10,new File("F:/temp"));        //2,聲明ServletFileUpload,接收上邊的臨時檔案。也可以預設值        ServletFileUpload up = new ServletFileUpload(disk);        //3,解析request        try {            List<FileItem> list = up.parseRequest(request);            //如果就一個檔案,            FileItem file = list.get(0);            //擷取檔案名稱:            String fileName = file.getName();            //擷取檔案的類型:            String fileType = file.getContentType();            //擷取檔案的位元組碼:            InputStream in = file.getInputStream();            //檔案大小            int size = file.getInputStream().available();            //聲明輸出位元組流            OutputStream out = new FileOutputStream(path+"/"+fileName);            //檔案copy            byte[] b = new byte[1024];            int len = 0;            while((len=in.read(b))!=-1){                out.write(b, 0, len);            }            out.flush();            out.close();                        //刪除上傳產生的臨時檔案            file.delete();                        //顯示資料            response.setContentType("text/html;charset=UTF-8");            PrintWriter pw = response.getWriter();            pw.println("檔案名稱:"+fileName);            pw.println("檔案類型:"+fileType);            pw.println("<br/>檔案大小(byte):"+size);        } catch (FileUploadException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

上傳檔案:

臨時目錄:

服務端:

響應:

實際項目中都是有檔案伺服器的,公司一般都提供了上傳到檔案伺服器介面,有的是上傳一個file類型,有的是流。

多檔案上傳:和單檔案一樣

表單:

controller:

/**     * 多檔案上傳     * @param request     * @param response     */    @RequestMapping("uploadMultipart")    public void uploadMultipart(HttpServletRequest request,HttpServletResponse response){        //擷取tomcat下的up目錄的路徑           String path = request.getSession().getServletContext().getRealPath("/up");        //1,聲明DiskFileItemFactory工廠類,用於在指定磁碟上設定一個臨時目錄        DiskFileItemFactory disk = new DiskFileItemFactory(1024*10,new File("F:/temp"));        //2,聲明ServletFileUpload,接收上邊的臨時檔案。也可以預設值        ServletFileUpload up = new ServletFileUpload(disk);        //3,解析request        try {            List<FileItem> list = up.parseRequest(request);            for (FileItem file : list) {                //擷取檔案名稱:                String fileName = file.getName();                //擷取檔案的類型:                String fileType = file.getContentType();                //擷取檔案的位元組碼:                InputStream in = file.getInputStream();                //使用工具類                FileUtils.writeByteArrayToFile(new File(path+"/"+fileName), file.get());                file.delete();            }        } catch (FileUploadException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }

測試,上傳3張圖片:

 

java檔案上傳-使用apache-fileupload組件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.