'Spring Rest Controller with Byte Array file
I am trying to send a byte array of a file content from angular to the rest api. But I am getting Http 403 forbidden. I don't have any security enabled. I am not sure what I am doing wrong. I tried couple of different MIME types. The below is the http post from angular js and the $scope.encoded_file has the file in byte array.
$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*****");}}
The request doesnt reach to the service of course and I dont know why I am getting 403. Any idea?
Added @CrossOrigin in before the service method but still no luck
Did the below added the CrossOrigin to the controller method.
public class DocUploadService {
@CrossOrigin(origins = "http://localhost:9200")
@RequestMapping(value="/docupload",method={RequestMethod.GET,RequestMethod.POST,RequestMethod.OPTIONS,RequestMethod.PUT},consumes="application/octet-stream")
Also, added global CORS registry.
@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);
}
Solution 1:[1]
Try adding a filter to avoid 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() {}
}
Or you can also use @CrossOrigin annotation:
@CrossOrigin(origins = "http://localhost:9200")
There is an example here:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

