ajax请求自定义请求头,服务器跨域配置

1.ajax发送请求,红色部分为自定义添加的请求头信息

//上传视频文件
     function uploadfile(el) {
     <@shiro.user>
         var userId = <@shiro.principal property = "id"/>
             </@shiro.user>
         var formData = new FormData();
         var file = $(el).siblings().filter('#filedata').prop('files')[0];
         formData.append("file", $(el).siblings().filter('#filedata').prop('files')[0]);
         if(file != null && file != ''){
             $.ajax({
                 url: "http://localhost:8088/jq/vo/up.do",
                 type: "POST",
                 headers: {
                     'Range': 0,
                     'Filename': file.name,
                     'Filelength': file.size,
                     'UserId': userId,
                 },
                 data: formData,
                 processData: false, // 不要对data参数进行序列化处理,默认为true
                 contentType: false, // 不要设置Content-Type请求头,因为文件数据是以 multipart/form-data 来编码
                 xhr: function () {
                     myXhr = $.ajaxSettings.xhr();
                     if (myXhr.upload) {
                         myXhr.upload.addEventListener('progress', function (e) {
                             if (e.lengthComputable) {
                                 var percent = Math.floor(e.loaded / e.total * 100);
                                 $(el).siblings().filter('#isfile').html('已上传:' + percent.toString() + '%');
                             }
                         }, false);
                     }
                     return myXhr;
                 },
                 success: function (resp) {
                     // console.log(resp,"---success----");
                     if (resp.flag == 1) {
                         $(el).siblings().filter('#successAlertFile').show().fadeOut(3000);//显示模态框
                         $(el).siblings().filter('#successAlertFile').children().css('color', 'green').html('上传成功!');
                         $(el).siblings().filter('#videoUrl').val(resp.data.path);
                     } else {
                         $(el).siblings().filter('#successAlertFile').show().fadeOut(3000);
                         $(el).siblings().filter('#successAlertFile').children().css('color', 'red').html('上传失败,请重新上传!');
                         $(el).siblings().filter('#isfile').html('');
                     }
                 },
                 error: function (res) {
                     // 请求失败
                     console.log(res);
                     $(el).siblings().filter('#successAlertFile').show().fadeOut(3000);
                     $(el).siblings().filter('#successAlertFile').children().css('color', 'red').html('上传失败,请重新上传!');
                     $(el).siblings().filter('#isfile').html('');
                 }
             });
         }else{
             $(el).siblings().filter('#successAlertFile').show().fadeOut(3000);
             $(el).siblings().filter('#successAlertFile').children().css('color', 'red').html('上传视频不能为空!');
         }

     }

2.服务器端配置,设置自定义请求都信息,解决跨域问题

    1.新建java类 CORSFilter.java 下面红色部分为服务器端配置的自定义请求头信息

   package com.enjoy.common;

    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;

/**
 * @Author: LBX
 * @Date: 2018/5/29 14:02
 */
public class CORSFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
 response.addHeader("Access-Control-Allow-Headers"," Access-Control-Allow-Headers,userid,range,filename, filelength,Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {
    }
    public void destroy() {
    }
}

        2,在web.xml文件里面添加以下信息,注意放到 同级<filter>标签的最上面

        <filter>
<filter-name>cors</filter-name>
<filter-class>com.enjoy.common.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

原文地址:https://www.cnblogs.com/hzcya1995/p/13300622.html