簡體   English   中英

如何從angularjs和CORS支持上載文件到jersey

[英]how to upload file to jersey from angularjs and CORS support

我正在嘗試創建上傳文件服務。 所以我在這里遵循服務器端指南 以及客戶端指南

但我在瀏覽器上收到該錯誤

XMLHttpRequest cannot load http://192.168.200.151:8080/documents/uploadDoc. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.

和服務器上的此錯誤
192.168.200.151 - - [03/Nov/2016:13:44:59 +0000] "OPTIONS /documents/uploadDoc HTTP/1.1" 200 13 "http://localhost:8383/mamagoose/admin/index.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36" 3

我知道我有CORS支持問題,但我不知道如何克服它。 我嘗試用這種依賴關系來編輯我的pom.xml,但是沒有運氣。

這一定是我想念任何人的主意嗎?

<!-- https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter -->
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>2.5</version>
</dependency>

客戶端

  uploadfile : function(action, files, success, error){

        var url = webServiceModuleAddress+"/uploadDoc";

        for ( var i = 0; i < files.length; i++)
        {
            var fd = new FormData();
            fd.append("file", files[i]);

            $http.post(url, fd, {

                withCredentials : false,

                headers : {
                    'Content-Type' : undefined
                    },
                    transformRequest : angular.identity
                   })
                   .success(function(data)
                   {
                    console.log(data);
                   })
                   .error(function(data)
                   {
                    console.log(data);
                   });
       }
    },

服務器端

@POST
@Path("/uploadDoc")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(@Context HttpServletRequest req, @QueryParam("callback") String callback,@FormDataParam("file") InputStream fileInputStream,@FormDataParam("file") FormDataContentDisposition contentDispositionHeader) throws JsonProcessingException 
{
    try{
        if(SessionManager.isUserConnected(req))
        {
            String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
            // save the file to the server
            documentsDao.saveFile(fileInputStream, filePath);
            String output = "File saved to server location : " + filePath;
            return ResourceResponse.getResourceJsonString(output, callback, "true", ErrorMessageEnum.SUCCESS);
        }
        else
        {
            return ResourceResponse.getResourceFailResponseString(callback, ErrorMessageEnum.USER_NOT_CONNECTED);
        }

    }catch(Exception e)
    {
        e.printStackTrace();
        return ResourceResponse.getResourceFailResponseString(callback, ErrorMessageEnum.FAILURE);

    }
}

如果您嘗試從一個域訪問另一個域,則會收到此錯誤。 這是服務器端的問題。 您不需要在cors的angular中添加任何標題。 您需要在服務器端添加標頭。 您所請求的服務器必須實現CORS才能從您的網站訪問權限中授予JavaScript。

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

請參閱此鏈接以了解如何實現一個-https://www.w3.org/wiki/CORS_Enabled

由於使用球衣,因此如何實現CORS的示例。 http://www.codingpedia.org/ama/how-to-add-cors-support-on-the-server-side-in-java-with-jersey/

這是一個很難解決的問題,但是如果有人遇到相同的問題,我會盡力幫助他人。

在服務器端的第一件事,我在util包中添加了該類

public class CORSResponseFilter implements ContainerResponseFilter {

    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)throws IOException
    {
        MultivaluedMap<String, Object> headers = responseContext.getHeaders();
        headers.add("Access-Control-Allow-Origin", "http://localhost:8383");//TODO:Need to find a replacement
        headers.add("Access-Control-Allow-Credentials", "true");
        //headers.add("Access-Control-Allow-Origin", "http://podcastpedia.org"); //allows CORS requests only coming from podcastpedia.org       
        headers.add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");          
        headers.add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    }

}

然后我們需要將課程注冊為提供者

environment.jersey().register(CORSResponseFilter.class);

這種配置為我解決了一個很大的問題。 因為即使我可以發送文件,我也無法獲得用戶的會話,也無法驗證請求,因此一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM