我正在尝试将文件内容的字节数组从angular发送到其余的api。但我禁止使用Http 403。我没有启用任何安全性。我不确定我做错了什么。我尝试了几种不同的MIME类型。以下是来自angular js的http帖子,$ scope.encoded_file具有字节数组中的文件。
$http({
method:'POST',
url:'http://localhost:9200/docupload',
data:{'content':$scope.encoded_file,'name':'test','type':'pdf'},
headers:{'Content-Type':'application/octet-stream'}
}).success(function(){});
};
DocUploadService
@RestController
public class DocUploadService {
@RequestMapping(value="/docupload",method={RequestMethod.GET,RequestMethod.POST},consumes="application/octet-stream")
public String UploadDocuments(@RequestParam(value="content")byte[] content,@RequestParam(value="type") String type,@RequestParam(value="name") String name) throws IOException
{
System.out.println("****Inside DocUpload*****");}}
请求当然没有达到服务,我不知道为什么我会收到403.有什么想法吗?
在服务方法之前添加了@CrossOrigin,但仍然没有运气
下面是否将CrossOrigin添加到控制器方法中。
public class DocUploadService {
@CrossOrigin(origins = "http://localhost:9200")
@RequestMapping(value="/docupload",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.OPTIONS,RequestMethod.PUT},consumes="application/octet-stream")
此外,添加了全球CORS注册表。
@EnableWebMvc
public class WebMVCconfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
// TODO Auto-generated method stub
registry.addMapping("/docupload")
.allowedOrigins("http://localhost:9200")
.allowedMethods("POST", "GET","OPTION","PUT");
super.addCorsMappings(registry);
}
答案 0 :(得分:0)
尝试添加过滤器以避免CORS:
@Component
public class SimpleCORSFilter 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, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Expose-Headers", "Location");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
或者你也可以使用@CrossOrigin注释:
@CrossOrigin(origins = "http://localhost:9200")
这里有一个例子: