Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Friday 30 November 2018

Upload base64 image to Google CDN in Java

/*Upload base64 image in CDN
Save cdn url to database*/

/*
path contain base64 encoded image
(i.e.
Strint path = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    9TXL0Y4OHwAAAABJRU5ErkJggg==";)


*/

class ImageAtCDN{

public String base64ToCDN(String path, String imageName){
 
    int extentionStartIndex = path.indexOf("data:image");
    int extensionEndIndex = path.indexOf(';');
    String fileExtension = path.substring(extentionStartIndex + 11, extensionEndIndex);


        String encodedString = path
        // tokenize the data     
        String parts = encodedString.tokenize(",");
        String imageString = parts[1];

        // create a buffered image     
BufferedImage image
        byte[] imageByte

        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();

        String uploadFolder = "uploads/shop_instructions";
        String fileName = imageName+"."+ fileExtension;

        // write the image to a file     
 def servletContext = WebUtils.retrieveGrailsWebRequest().getServletContext();
        String imagePath = servletContext.getRealPath(uploadFolder);
        File outputfile = new File(imagePath+"/"+fileName);
        if (!outputfile.exists()) {
            outputfile.mkdirs();
        }
        ImageIO.write(image, fileExtension, outputfile);
        String bucketName = "cdn.xyz.com";
        GoogleFileHelper.uploadFile(uploads/shop_instructions/base/0/0/50/+fileName,outputfile,bucketName);
        if (outputfile.exists()) {
            outputfile.delete()
        }
     
        return path
 
}

}



class GoogleFileHelper{


/*  The below snippets of code will upload the file to the google.    * */


    public static uploadFile(String name,  File file, String bucketName)
            throws IOException, GeneralSecurityException {
/*     The below is the unix command to get the mime type of the file. So below we are using the native command to execute.*/     

 def contentType = file.toURL().openConnection().getContentType()

        println("Content type=="+contentType)

        InputStreamContent contentStream = new InputStreamContent(
                contentType, new FileInputStream(file));

        // Setting the length improves upload performance        contentStream.setLength(file.length());
        StorageObject objectMetadata = new StorageObject()
        // Set the destination object name     
         .setName(name)
        // Set the access control list to publicly read-only             
        .setAcl(Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
        // Do the insert     
        Storage client = StorageFactory.getService();
        Storage.Objects.Insert insertRequest = client.objects().insert(bucketName, objectMetadata, contentStream);
        insertRequest.execute();
    }


}

No comments:

Post a Comment