1. 程式人生 > >SpringMVC-實現PUT請求上傳文件(轉)

SpringMVC-實現PUT請求上傳文件(轉)

Enctype multi think pic 不可 form OS his win

因為在圖片上傳的時候使用的是二進制的方式上傳,所以使用隱藏域進行方法轉換方式失效,轉方法:

https://www.cnblogs.com/morethink/p/6378015.html

可是後來我又有遇到另外一個需求那就是修改的時候需要傳送文件到put方法中,於是這種方法就不可行了,但是我在HiddenHttpMethodFilter源碼中看到這樣一句話

1  * <p><b>NOTE: This filter needs to run after multipart processing in case of a multipart
2  * POST request, due to its inherent need for
checking a POST body parameter.</b> 3 * So typically, put a Spring {@link org.springframework.web.multipart.support.MultipartFilter} 4 * <i>before</i> this HiddenHttpMethodFilter in your {@code web.xml} filter chain.

和MultipartFilter源碼中這樣的註釋

1  /**
2      * Set the bean name of the MultipartResolver to fetch from Spring‘s
3 * root application context. Default is "filterMultipartResolver". 4 */

  1. 也就是說我們可以通過在web.xml中註冊一個MultipartFilter,一定要在HiddenHttpMethodFilter之前

     1 <filter>
     2     <filter-name>MultipartFilter</filter-name>
     3     <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class
    > 4 </filter> 5 <filter-mapping> 6 <filter-name>MultipartFilter</filter-name> 7 <servlet-name>dispatcher</servlet-name> 8 </filter-mapping> 9 10 <filter> 11 <filter-name>HiddenHttpMethodFilter</filter-name> 12 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 13 </filter>
  2. 然後再在Spring的 root application context中添加如下代碼

    <bean id="filterMultipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="209715200"/>
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="resolveLazily" value="true"/>
    </bean>
  3. FormData對象是html5的一個對象,目前的一些主流的瀏覽器都已經兼容。FormData對象是html5的一個對象,目前的一些主流的瀏覽器都已經兼容。

     function test() {
            var form = new FormData(document.getElementById("tf"));
            form.append("_method", ‘put‘);
            $.ajax({
                url: url,
                type: ‘post‘,
                data: form,
                processData: false,
                contentType: false,
                success: function (data) {
                    window.clearInterval(timer);
                    console.log("over..");
                },
                error: function (e) {
                    alert("錯誤!!");
                    window.clearInterval(timer);
                }
            });
            get();//此處為上傳文件的進度條
        }
    <form id="tf" method="post" name="formDada" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="text" name="id"/>
        <input type="text" name="name"/>
        <input type="button" value="提" onclick="test()"/>
    </form>

最後,就可以實現將文件上傳提交給put方法。

SpringMVC-實現PUT請求上傳文件(轉)