Ошибка CORS для multipart/form-data в API Джерси

Я пытаюсь загрузить файл excel, но в API-интерфейсе Джерси возникает ошибка CORS. Я вызываю API из angular 4 с заголовками multipart/form-data и добавляю фильтр для каждого входящего запроса к 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;
        }
}

Заголовки ответа:

Заголовок ответа в браузере


person Nishant Varshney    schedule 24.02.2018    source источник
comment
Вы подтвердили, что заголовок действительно получен браузером? Проверьте заголовки ответа в сетевой консоли вашего любимого браузера.   -  person Akshaya Shanbhogue    schedule 24.02.2018
comment
@Akshay... Я обновил заголовки запроса/ответа, полученные браузером...   -  person Nishant Varshney    schedule 24.02.2018


Ответы (1)


У меня то же самое в моем проекте, мы используем следующие заголовки

"Access-Control-Allow-Origin" : "*"
"Access-Control-Allow-Headers" : "Origin, X-Requested-With, Content-Type, Accept"

Возможно, вам просто не хватает Origin в Access-Control-Allow-Headers

person Bentaye    schedule 08.03.2018