I am trying to store base64 encoded image to azure blob storage. PFB the code snippet for the same. File is getting created but it is coming as broken image.
Code Snippet
String mimeType = extractMimeType(imageBase64Encoded).replace("image/", "");
String fileName = "image." mimeType;
BlobContainerClient containerClient = new BlobContainerClientBuilder()
.connectionString(connectionString)
.containerName(containerName)
.buildClient();
BlobClient client = containerClient.getBlobClient(fileName);
String base64Data = imageBase64Encoded.split(",")[1];
byte[] base64DataBytes = base64Data.getBytes();
ByteArrayInputStream dataStream = new ByteArrayInputStream(base64DataBytes);
client.upload(dataStream, base64DataBytes.length);
CodePudding user response:
You need to decode the base64 encoded string to byte[] and use that byte[] to store the image.
String mimeType = extractMimeType(imageBase64Encoded).replace("image/", "");
String fileName = "image." mimeType;
BlobContainerClient containerClient = new BlobContainerClientBuilder()
.connectionString(connectionString)
.containerName(containerName)
.buildClient();
BlobClient client = containerClient.getBlobClient(fileName);
String base64Data = imageBase64Encoded.split(",")[1];
byte[] base64DataBytes = Base64.getDecoder().decode(base64Data);
ByteArrayInputStream dataStream = new ByteArrayInputStream(base64DataBytes);
client.upload(dataStream, base64DataBytes.length);