XMLHTTPRequest

时间:2016-08-05 19:42:39

标签: java servlets xmlhttprequest cross-domain

我正在尝试将文本和文件发送到Java Servlet。在同一台服务器上工作时,这种方法很好,但现在我遇到了跨域访问问题。

我已经在servlet中设置了标题,这通常在发送纯文本时有效,但是我必须发送一个文件,考虑到multipart \ form数据仍在给我“No”Access -Control-Allow-Origin'标头出现在请求的资源上。“错误。所以我需要设置标题来容纳表单数据,但其他页面和教程似乎只是说标题应该是什么样的,而不是如何设置它。这是我的代码:

Upload.js

var fd = new FormData();
fd.append("id", fA[0].name.split('.')[0]);
fd.append("frame", fA[0].size);
fd.append('file', fA[0]);
var request = new XMLHttpRequest();
request.open("POST", "http://myserver:myport/Upload", true);
var sBoundary = "---------------------------" + Date.now().toString(16);
request.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
request.send(fd);

Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            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");
            //the rest of my code
 }

0 个答案:

没有答案