SpringMVC-实现PUT请求上传文件(转)

因为在图片上传的时候使用的是二进制的方式上传,所以使用隐藏域进行方法转换方式失效,转方法:

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方法。

猜你喜欢

转载自www.cnblogs.com/thyHome/p/9098061.html
今日推荐