【SpringMVC學習08】SpringMVC中實現文件上傳

 之前有寫過一篇struts2實現的文件上傳,這一篇博文主要來總結下springmvc實現文件上傳的步驟。首先來看一下單個文件的上傳,然後再來總結下多個文件上傳。

1. 環境準備

  springmvc上傳文件的功能需要兩個jar包的支持(點我下載),如下 
jar包

2. 單個文件的上傳

2.1 前臺頁面

  簡單的寫一下前臺頁面,注意一點的是form表單中別忘了寫enctype="multipart/form-data"屬性:

<tr>
    <td>商品圖片</td>
    <td><c:if test="${itemsCustom.pic !=null}">
            <img src="/file/${itemsCustom.pic}" width=100 height=100 /><br />
        </c:if> 
        <input type="file" name="items_pic"/>
    </td>
</tr>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2.2 對多部件類型multipart解析

  意思就是說針對上面的enctype="multipart/form-data"類型,springmvc需要對multipart類型的數據進行解析,在springmvc.xml中配置multipart類型解析器即可。

<!-- 文件上傳,需要配置MultipartResolver處理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 設置船上文件的最大尺寸爲5MB -->
    <property name="maxUploadSize" value="5242880"/>
    <property name="defaultEncoding" value="utf-8"/>   
</bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2.3 創建文件保存的虛擬目錄

  在上傳文件之前,首先要創建一個虛擬目錄來保存文件,這個虛擬目錄會對應磁盤上的一個實際的目錄,在實際中肯定會有一個服務器專門存儲資源的,在這裏我們就用本地來保存文件,然後映射一個虛擬目錄,用來在程序中指定獲取文件的路徑(其實上面前臺頁面中,那個src=”/file/${itemsCustom.pic}”中的/file就是虛擬目錄)。 
創建的方法有兩種:一是在Myeclipse中雙擊tomcat服務器,然後彈出下面的框框: 
虛擬目錄
  設置好後,保存即可,這樣上傳的文件都會保存到Document base指定的目錄中,相當於虛擬映射到path指定的目錄中,程序中獲取這個文件,要從path指定的虛擬目錄中獲取,即我上面的/file。 
  第二種方法就是在tomcat的配置文件中配置一下,其實剛剛在Myeclipse中的操作已經自動寫到這個配置文件中了,配置文件位置在tomcat目錄/conf/server.xml中,看一下里面會多了一行: 
配置 
  這就是剛剛我配置的,它自動寫到這個文件中了,所以我們也可以直接自己在文件中寫,就不需要在Myeclipse中配置了。

2.4 編寫後臺Controller方法

  接下來就是重點了,前臺傳過來的文件,我們在controller中需要進行處理,然後保存到磁盤中,同時也就映射到了我們配置的虛擬路徑中了,那麼如何接收呢?看下面的代碼:

@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model, HttpServletRequest request,
        Integer id,
        @Validated(value = { ValidGroup1.class }) ItemsCustom itemsCustom,
        BindingResult bindingResult, 
        MultipartFile items_pic)
        throws Exception {

    // 處理上傳的單個圖片    
    String originalFileName = items_pic.getOriginalFilename();// 原始名稱
    // 上傳圖片
    if (items_pic != null && originalFileName != null && originalFileName.length() > 0) {
        // 存儲圖片的物理路徑,實際中是要寫到配置文件中的,不能在這寫死
        String pic_path = "E:\\github\\develop\\upload\\temp\\";
        // 新的圖片名稱
        String newFileName = UUID.randomUUID()
                + originalFileName.substring(originalFileName
                        .lastIndexOf("."));     
        File newFile = new File(pic_path + newFileName);//新圖片   
        items_pic.transferTo(newFile);// 將內存中的數據寫入磁盤
        itemsCustom.setPic(newFileName);// 將新圖片名稱寫到itemsCustom中
    } else {
        //如果用戶沒有選擇圖片就上傳了,還用原來的圖片
        ItemsCustom temp = itemsService.findItemsById(itemsCustom.getId());
        itemsCustom.setPic(temp.getPic());
    }

    // 調用service更新商品信息,頁面需要將商品信息傳到此方法
    itemsService.updateItems(id, itemsCustom);
    return "/WEB-INF/jsp/success.jsp";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

  首先來看一下形參,主要有ItemsCustom和MultipartFile類型的items_pic,我這裏上傳一張圖片是ItemsCustom類的一個屬性,所以有了這個形參,是爲了寫到該類中,另外前面的@Validated註解是我寫springmvc校驗的時候用的,跟這裏文件上傳無關。springmvc文件上傳的類是MultipartFile,名items_pic必須和前臺的name屬性一致纔行。 
  上傳文件的邏輯是,首先判斷有沒有上傳文件,如果上傳了,那麼對文件重新命名然後寫到磁盤中。如果沒有上傳文件,那麼我應該還是用原來的文件(圖片),因爲我寫的這個例子是更新商品信息,對文件上傳那裏沒有做非空驗證,所以在這裏寫了else。 
  這樣文件就上傳完了,這是單個文件的上傳。

3. 多個文件的上傳

  多個文件上傳和單個文件上傳原理一樣的,不過在細節上會有點不同,待我一個個總結。首先在前臺頁面上要注意的一點是name屬性必須一樣,即:

<input type="file" name="items_pic"/>
<input type="file" name="items_pic"/>
  • 1
  • 2

  然後就是後臺接收的形參也要變,如下:

@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model, HttpServletRequest request,
        Integer id,
        @Validated(value = { ValidGroup1.class }) ItemsCustom itemsCustom,
        BindingResult bindingResult, 
        @RequestParam MultipartFile[] items_pic)
        throws Exception {  

    //多個圖片,不存數據庫了,在此打印一下即可
    for(MultipartFile myfile : items_pic) {
        if(myfile.isEmpty()){  
            System.out.println("文件未上傳");  
        }else{  
            System.out.println("文件長度: " + myfile.getSize());  
            System.out.println("文件類型: " + myfile.getContentType());  
            System.out.println("文件名稱: " + myfile.getName());  
            System.out.println("文件原名: " + myfile.getOriginalFilename());  
            System.out.println("========================================");  

            //寫入磁盤,和上面的單個文件上傳一模一樣
            String originalFileName = myfile.getOriginalFilename();
            String pic_path = "E:\\github\\develop\\upload\\temp\\";
            String newFileName = UUID.randomUUID()
                    + originalFileName.substring(originalFileName
                            .lastIndexOf("."));
            File newFile = new File(pic_path + newFileName);
            myfile.transferTo(newFile);
        }  
    }   

    return "/WEB-INF/jsp/success.jsp";
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

  如上,形參變成數組類型了,且前面要加上@RequestParam註解纔行。然後獲取的話,就是遍歷這個數組,循環內部與上面的單個文件上傳就一模一樣了。看一下打印結果: 
結果 
  可以看到,兩個文件都順利接收到,至此,多文件上傳成功。關於springmvc的文件上傳功能就總結到這吧。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章