Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue while downloading Image

Tags:

java

cors

tomcat7

I have an API which converts base64 string to image and write the image in Tomcat Server.The image writes successfully after calling API but gives the error while retrieving the same image follows:

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. XMLHttpRequest cannot load http://hostname:4444//tmpFiles/31487660124865.jpg. No 'Access-Control-Allow-Origin' header is present on the requested resource.

My code is as follows:

public Message uploadImage(Map<String, String> map) {

    // Initializing the message
    Message message = new Message();

    try {

        // Get the file data
        String fileData = map.get("file_data");

        // Split the data with the comma
        String base64Image = fileData.split(",")[1];

        // Convert the base64 input to binary
        byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

        BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));

        // Manipulations in File Name
        String fileName = map.get("file_name");
        String file = fileName.substring(0, fileName.indexOf("."));
        String fileExtension = fileName.substring(fileName.indexOf("."));

        // Get the current time
        Long time = new Date().getTime();

        // Write the file name with the current time to avoid redundancy
        String maniputedFileName = file + "" + time + fileExtension;
        System.out.println("manipulated file name is " + maniputedFileName);

        // Check if file name is not empty
        if (!maniputedFileName.isEmpty()) {

            // Get the root path of tomcat server
            String rootPath = System.getProperty("catalina.home");

            System.out.println("root Path:- " + rootPath);

            // File Directory/Path on tomcat server
            File fileDirectory = new File(rootPath + File.separator + "webapps/tmpFiles");

            // If file direcory does not exist
            if (!fileDirectory.exists())
                fileDirectory.mkdirs();

            File outputfile = new File(fileDirectory.getAbsolutePath() + File.separator + maniputedFileName);

            // Write created image on server
            ImageIO.write(image, "png", outputfile);

            // Set the success message
            message.setDescription("You successfully uploaded file=" + maniputedFileName);
            message.setObject(outputfile.getAbsolutePath());
            message.setValid(true);
            return message;

        }
        // Set the failure message
        else {
            message.setDescription("You failed to upload " + maniputedFileName + " because the file was empty.");
            message.setValid(false);
            return message;
        }
    }
    // Handling all exceptions
    catch (IOException e) {
        message.setDescription(e.getMessage());
        message.setValid(false);
        return message;
    }
}

And web.xml is:

     <filter>
        <filter-name>tokenfilter</filter-name>
        <filter-class>com.springiot.filter.TokenFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>tokenfilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
    <filter-name>SimpleCORSFilter</filter-name>
    <filter-class>com.springiot.filter.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SimpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And my tokenFilter Class is :

 HttpServletResponse response = (HttpServletResponse) res;

    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET,OPTIONS, DELETE");
    response.addHeader("Access-Control-Max-Age", "3600");
    response.addHeader("Access-Control-Allow-Headers",
            "Content-Type, Access-Control-Allow-Headers, Authorization,X-Requested-With,token,userKey,user_id");
like image 677
Tanvi Garg Avatar asked Mar 21 '17 10:03

Tanvi Garg


People also ask

How do I fix the CORS error?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

How do I fix CORS error on Chrome?

Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs). Installing this add-on will allow you to unblock this feature.

What is CORS image?

The HTMLImageElement interface's crossOrigin attribute is a string which specifies the Cross-Origin Resource Sharing (CORS) setting to use when retrieving the image.

What is the reason for CORS error?

If the CORS configuration isn't setup correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the CORS security rules.


1 Answers

You need to add the filter in web.xml in CATALINA_HOME/conf with proper path name or just /*. Add filter like below

  ...

 <filter>
   <filter-name>CorsFilter</filter-name>
   <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
 </filter>
 <filter-mapping>
   <filter-name>CorsFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

...

For more info check this official document

like image 53
Shettyh Avatar answered Sep 23 '22 08:09

Shettyh