Jersey API中的多部分/表单数据出现CORS错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jersey API中的多部分/表单数据出现CORS错误相关的知识,希望对你有一定的参考价值。
我正在尝试上传一个excel文件,但是在Jersey API中出现了CORS错误。我正在使用带有multipart / form-data标头的angular 4调用API,并为每个传入的JAVA Rest API请求添加了一个过滤器。找到下面的代码并帮助我:
Angular API调用:
export class DboperationService {
private headers1 = new Headers({'Content-Type' : 'multipart/form-data'});
sendFile(fileObj: File){
return this._http.post(this.baseURL+'/submitexcel', fileObj,{headers : this.headers1}).map(res => res.json().data).subscribe();
}
}
REST API:
@POST
@Path("/submitexcel")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
// check if all form parameters are provided
System.out.println("CAssked");
if (uploadedInputStream == null || fileDetail == null)
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
try {
createFolderIfNotExists(UPLOAD_FOLDER);
} catch (SecurityException se) {
System.out.println("Can not create destination folder on server");
return Response.status(500)
.entity("Can not create destination folder on server")
.header("Access-Control-Allow-Origin", "*")
.build();
}
String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName();
/*try {
//saveToFile(uploadedInputStream, uploadedFileLocation);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}*/
System.out.println("File saved to:"+uploadedFileLocation);
return Response.status(200)
.entity("File saved to " + uploadedFileLocation)
.header("Access-Control-Allow-Origin", "*")
.build();
}
跨源过滤器:
package com.newgen.aproj2;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
public class CrossOrigin implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest creq, ContainerResponse cresp) {
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
return cresp;
}
}
响应标题:
答案
我的项目有同样的事情,我们使用以下标题
"Access-Control-Allow-Origin" : "*"
"Access-Control-Allow-Headers" : "Origin, X-Requested-With, Content-Type, Accept"
也许你只是错过了Origin
中的Access-Control-Allow-Headers
以上是关于Jersey API中的多部分/表单数据出现CORS错误的主要内容,如果未能解决你的问题,请参考以下文章
快速文件上传java rest api mimepull关闭问题与多部分表单数据
Jersey API 中的 multipart/form-data 出现 CORS 错误