springmvc - 文件上傳

#Springmvc 文件上傳簡介 使用servlet3 的 javax.servlet.http.Part API 接口實現文件上傳。使用 multipart編碼文件。html

默認在單個請求中,只處理每一個文件最大1Mb,最多10Mb的文件數據。java

你能夠覆蓋那些值,也能夠設置臨時文件存儲的位置(好比,存儲到/tmp文件夾下)及傳遞數據刷新到磁盤的閥值(經過使用MultipartProperties類暴露的屬性)。git

若是你須要設置文件不受限制,能夠設置spring.http.multipart.max-file-size屬性值爲-1。web

#項目實例spring

##需求:在修改商品頁面添加修改商品信息功能數據庫

##springmvc 對多部件內容的解析spring-mvc

1、在jsp頁面配置enctype對多部件上傳的支持mvc

<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post"
      enctype="multipart/form-data">
    <input type="hidden" name="id" value="${itemsCustom.id }"/>
    修改商品信息:
    <table width="100%" border=1>

2、在springmvc.xml中配置multipart解析器dom

<!-- 圖片上傳解析器-->
<bean id="mulitpartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="MaxUploadSize">
        <!-- 設爲5M -->
        <value>5242880</value>
    </property>
</bean>

3、建立圖片的虛擬目錄jsp

在conf/server.xml 中,添加 <Context docBase="物理目錄" path="/pic" reloadable="false"/>

4、具體實現

springmvc.xml 文件的配置

<!-- 圖片上傳解析器-->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="MaxUploadSize">
        <!-- 設爲5M -->
        <value>5242880</value>
    </property>
</bean>

editItems.jsp 的配置

<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post"
      enctype="multipart/form-data">
<tr>
    <td>商品圖片</td>
    <td>
        <c:if test="${itemsCustom.pic !=null}">
            <img src="/pic/${itemsCustom.pic}" width=160 height=200/>
            <br/>
        </c:if>
        <input type="file"  name="items_pic"/>
    </td>
</tr>

controller方法

public String editItemsSubmit(Model model, HttpServletRequest request, Integer id,
                              @ModelAttribute("itemsCustom") @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:\\Zen-Events\\Pictures\\tmp";
    //新的圖片名稱
    String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
    //新的圖片存儲地址
    File newFile = new File(pic_path, newFileName);
    //將圖片寫入到磁盤中
    items_pic.transferTo(newFile);
    //將圖片名稱寫入到數據庫對象中
    itemsCustom.setPic(newFileName);
}

5、我的理解

經過頁面上傳圖片: <input type="file" name="items_pic"/>

在controller中: 上傳組件的文件必須以 MultipartFile 這個類型來存儲,以及傳遞處理數據。

由此,springmvc才 能夠解析這個文件。

相關文章
相關標籤/搜索