user2395365
user2395365

Reputation: 2149

How to set content type using Azure Java azure-storage-blob SDK

My code looks like:

    try {
        MultipartFile file = uploadFileInfo.getUploadFile();
        InputStream inputStream = new BufferedInputStream(file.getInputStream());
        BlobProperties props = blockBlobClient.getProperties();
        blockBlobClient.upload(inputStream, file.getBytes().length);
    } catch (IOException e) {
        log.error("Unable to upload blob!", e);
        return baseResp;
    }

However the file contentType is application/octet-stream, and I need to set it to "image/jpg". How can I do this with the Java SDK?

Upvotes: 2

Views: 1373

Answers (2)

lukas84
lukas84

Reputation: 425

The upload method does not provide this option, you need to use the uploadWithResponse method, which allows you to specify this and many other parameters. Here's an example:

ParallelTransferOptions parallelTransferOptions = new ParallelTransferOptions();
BlobHttpHeaders headers = new BlobHttpHeaders().setContentType(MediaType.IMAGE_JPEG_VALUE);
Map<String, String> metadata = Collections.singletonMap("metadata", "value");
BlobRequestConditions requestConditions = new BlobRequestConditions();
Context context = new Context("key", "value");
Duration timeout = Duration.ofSeconds(60);

blobClient.uploadWithResponse(inputStream, size, parallelTransferOptions, headers, metadata, AccessTier.HOT, requestConditions, timeout, context);

Upvotes: 1

Gaurav Mantri
Gaurav Mantri

Reputation: 136186

To upload a blob and set it's content type, please use the following method: BlockBlobClient.uploadWithResponse. Here's the sample code (taken from the same link):

BlobHttpHeaders headers = new BlobHttpHeaders()
     .setContentType("image/jpg");
 
 Map<String, String> metadata = Collections.singletonMap("metadata", "value");
 
 byte[] md5 = MessageDigest.getInstance("MD5").digest("data".getBytes(StandardCharsets.UTF_8));
 
 BlobRequestConditions requestConditions = new BlobRequestConditions();
 Context context = new Context("key", "value");
 client.uploadWithResponse(data, length, headers, metadata, AccessTier.HOT, md5,
         requestConditions, timeout, context);

Upvotes: 2

Related Questions