XMLHTTPRequest为CORS设置适当的标头

时间:2016-11-09 14:28:54

标签: javascript java upload xmlhttprequest cors

尝试上传文件时收到CORS错误。我在其他页面上设置的正常标头响应似乎无法正常工作,我相信我需要在HTTPRequest中正确编写标头,但我不确定如何。应该是在我打开我能说的请求之后。这是我的代码:

UploadDocument.js

   var fd = new FormData();
   var pro = $("#pro").val(); 

   fileArray[index].submit = true; 

   fd.append("name" + index, "pdf2");
   fd.append("size" + index, fileArray[index].size);
   var fileDate = new Date(fileArray[index].lastModifiedDate);
   var currentDate = new Date();
   fd.append("fileDate" + index, fileDate.getTime());
   fd.append("uploadDate" + index, currentDate.getTime());
   fd.append("officialDate" + index, $('#date').val());
   fd.append("extension" + index, fileArray[index].name.split('.')[1]);
   fd.append("program_id" + index, pro);
   fd.append('file' + index, fileArray[index]);    

   fd.append("length", fileArray.length);
   var request = new XMLHttpRequest();
   request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            that.prop('disabled', true);
            that.text("Done!");
            that.parent().siblings().children(".deleteBtn").prop("disabled", true); 
        }
     };
   request.open("POST", locationOfServlet, true);
   request.send(fd);

以下是我如何处理servlet中的标头:

RecieveFiles.java

        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS, DELETE");
        response.addHeader("Access-Control-Max-Age", "86400");

1 个答案:

答案 0 :(得分:0)

可能会帮助您https://developer.mozilla.org/enUS/docs/Web/API/FormData/Using_FormData_Objects

您是否在表单中指定了“multipart / form-data”属性?

<form enctype="multipart/form-data">