跨平台Ajax上传不起作用



我正在Spring Rest服务上使用Ajax上传来开发上传功能。它在开发服务器上工作得很好,但一旦在集成服务器上,它的配置与生产类似,需要一个跨平台调用,我就会得到可怕的

XMLHttpRequest cannot load http://xxxxxxxxxx:7001/felixmetier/rest/upload/montants. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://yyyyyyy' is therefore not allowed access. The response had HTTP status code 500.

在我的Javascript控制台中。

这里有一段JSP和上传的Javascript代码:

var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.withCredentials = true;
xhr.open('POST', '<%=Environment.getServiceParameter("FELIX", "rest.service.saisieMontants.upload.url")%>', true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open('POST', '<%=Environment.getServiceParameter("FELIX", "rest.service.saisieMontants.upload.url")%>');
} else {
throw new Error('Accès cross-platform interdit sur ce navigateur. Utilisez un navigateur plus récent (IE 8+, Chrome 3+, Firefox 3.5+, Safari 4+).');
}
xhr.onload = function () {
activateFormButtonsAndLinks();
document.getElementById('fwkWaitingScreen').style.display = 'none';
var response = this.responseText;
var data = JSON.parse(response);
if (data.status===1) {
alert("Erreur générale lors du chargement (pas de mise à jour en BDD) : "+data.message);
} else {
var msg = "Chargement terminé.nnNb de lignes traitées : "+data.totLines+"nNb de lignes déjà controlées : "+data.totControlled+"nNb de lignes inexistantes en BDD : "+data.totIgnored
if (data.status===2) {
msg = msg + "nn"+data.totError+" erreur se sont produires lors du chargement. Lignes en erreur (max. "+data.maxError+" affichées) : "+data.errorLines
} else {
msg = msg + "nn"+"Chargement OK";
}
alert(msg);
}
var rechBouton = document.getElementsByName("recherche").item(0);
doAction(rechBouton, '','rechercherbouton');
}
xhr.send(formData);

来自Spring控制器:

@Controller
public class MontantsUploadController {
...
@RequestMapping(value = "/upload/montants", method = RequestMethod.POST)
public ResponseEntity<?> upload(@RequestParam("file_up") MultipartFile file, HttpServletRequest request) {
InputStream is;
SaisieMontantsUploadRestResponse feedback = null;
try {
is = file.getInputStream();
Reader reader = new InputStreamReader(is);
feedback = parseImportedFile(reader, "guest", getLocale(request));
} catch (IOException e) {
feedback = new SaisieMontantsUploadRestResponse();
feedback.setMessage("Impossible de lire le fichier attaché");
feedback.setStatus(SaisieMontantsUploadRestResponse.STATUS_GENERAL_ERROR);
log.error("Impossible de traiter le CSV", e);
}
backupFile(file);
return new ResponseEntity<SaisieMontantsUploadRestResponse>(feedback, HttpStatus.OK);
}
...
}

来自我的web.xml:

<filter>
<filter-name>CORS</filter-name>
<filter-class>fr.xxxx.felix.ejb.restjson.filter.CorsFilter</filter-class>
</filter>
<!-- Applying the CORS Filter to All REST URL -->
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>

这里是来自过滤器的代码:

public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "30");
filterChain.doFilter(request, response);
}
}

我使用的是Java7、Tomcat7和Spring3.0.4。

编辑:我刚刚看到,如果我记录(我不能在该服务器上调试)request.getHeader("Access-Control-Request-Method"),它是空的。但request.getMethod()返回"POST"。这正常吗?

Edit 2:我的rest调用使用POST方法,该方法具有多部分/表单数据内容类型,没有自定义标头,因此不需要飞行前调用。无论如何,我通过添加一个自定义标头并在我的Access Control Allow Headers响应标头中对其进行授权,强制进行了飞行前调用。现在,我可以在浏览器的网络控制台中看到这两个调用。奇怪的是:我的preflight OPTIONS调用通过了,没有任何问题,但我的POST调用仍然导致"请求的资源上不存在‘Access Control Allow Origin’标头"。我真的不明白。

编辑3:好了,现在我们有进展了。在跨域情况下,浏览器似乎将服务器的500错误误解为跨域错误。当我查看localhost.log时,我实际上看到了一个异常:

org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file_up' is not present
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseMissingParameterException(AnnotationMethodHandlerAdapter.java:715)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:511)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:340)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:427)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:415)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:788)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:717)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at fr.xxxxx.felix.ejb.restjson.filter.CorsFilter.doFilterInternal(CorsFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

现在的问题是:我可以在Chrome的网络视图中看到我的请求中名为"file_up"的多部分文件,所以我仍然不明白为什么它不起作用。

请求有效载荷:

------WebKitFormBoundaryi7iVj0nFvRL8zcuy
Content-Disposition: form-data; name="file_up"; filename="test_SAISIE_DES_MONTANTS.csv"
Content-Type: application/vnd.ms-excel

------WebKitFormBoundaryi7iVj0nFvRL8zcuy--

神秘感越来越浓。。。

试用
response.addHeader("Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition, Content-Description");

我认为您也需要在方法中添加OPTIONS

我终于解决了我的问题。事实证明,这不是一个真正的跨域问题,但浏览器将500内部错误误解为跨域访问错误,当发生跨域调用并发生500错误时,通常会发生这种情况。在处理跨域错误时需要记住的一点。

我真正的问题是一个简单的Spring配置问题,但不知何故,丢失的参数并没有阻止代码在我的本地Tomcat安装中工作,我仍然不理解。

相关内容

  • 没有找到相关文章

最新更新