上传文件,有时候需要跨二级域名访问,因为安全策略,需要做一些策略的调整。比如tomcat或者Nginx又或者代码。

    1,tomcat 目录 conf/web.xml中,

    最前面添加。
    <filter>
            <filter-name>CorsFilter</filter-name>
            <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
            <init-param>
                <param-name>cors.allowed.methods</param-name>
                <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
            </init-param>
            <init-param>
                <param-name>cors.allowed.headers</param-name>
                <param-value>Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
            </init-param>
            <async-supported>true</async-supported>
        </filter>
        <filter-mapping>
            <filter-name>CorsFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
     
    2,nginx 支持跨域访问
         2.1 在nginx.conf 
            http{
                  add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Headers X-Requested-With;
                add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
            }
        2.1 在子域名访问域名下
        
         location / {
                 add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Methods' 'POST,GET';
                    proxy_pass  http://file.bdbvip.com;
                    proxy_redirect     off;
                    proxy_set_header   Host             $host;
                    proxy_set_header   X-Real-IP        $remote_addr;
                    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
     
           }
    3,代码头部申明

    //response.setHeader("Access-Control-Allow-Origin", "blog.xuahua.com,cus.xuahua.com"); 仅允许指定的二级域名可以跨域
    response.setHeader("Access-Control-Allow-Origin", "*"); //允许所有的
    response.setHeader("Access-Control-Allow-Methods","POST"); //指定请求方法
    response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");

    联系QQ:343886028 --加QQ群 145315854