Christian
Christian

Reputation: 914

Set content-disposition header on upload to azure blob storage with spring-cloud-azure

I use spring boot 3.2.6 and implementation("com.azure.spring:spring-cloud-azure-starter-storage-blob:5.11.0")

I want to upload blobs to azure storage with the content-disposition property set to attachment with a given filename so I can have unique identifiers (uuid) for the blobs on azure, but when downloaded a "speaking" filename.

Currently, this works but as I understand it those are two requests, is it possible to set this on upload?

val blobClient = blobServiceClient.getBlobContainerClient(containerName).getBlobClient(blobPath)

if (blobClient.exists()) throw AzureStorageBlobAlreadyExistsException(blobPath)

try {
    blobClient.upload(file.inputStream(), file.size.toLong())
    blobClient.setHttpHeaders(BlobHttpHeaders().apply { contentDisposition = "attachment; filename=test.jpg'" })
} 

Moving setHttpHeaders before the upload results in a 404 blob not found.

Upvotes: 0

Views: 98

Answers (1)

Venkatesan
Venkatesan

Reputation: 10455

Currently, this works but as I understand it those are two requests, is it possible to set this on upload?

You can upload the blob with content-disposition in a single request using below java code.

You can use the uploadWithResponse method to upload both file and content-disposition property.

Code:

 BlobContainerClient  containerClient  =  blobServiceClient.getBlobContainerClient(containerName);
 BlobClient  blobClient  =  containerClient.getBlobClient(blobPath);
 try (InputStream  fileStream  =  new  FileInputStream(localFilePath)) {
 
     BlobHttpHeaders  headers  =  new  BlobHttpHeaders().setContentDisposition("attachment; filename="  +  displayFilename);
     BlobParallelUploadOptions  options  =  new  BlobParallelUploadOptions(fileStream)
     .setHeaders(headers);
     blobClient.uploadWithResponse(options, null, null);
     
     System.out.println("File uploaded successfully with content-disposition set.");
     } catch (Exception  e) {
     e.printStackTrace();
     }

Output:

File uploaded successfully with content-disposition set.

enter image description here

Portal: enter image description here

Upvotes: 1

Related Questions