How to send pdf response from a Azure Function java?

Can someone let me know how to send pdf response from a HTTP Trigger Azure function in Java.

Once the function is triggered, I need to read a pdf from Azure storage and return the pdf as response to the browser.

Upvotes: 0

Views: 1354

Answers (1)

hujtomi
hujtomi

Reputation: 1570

This works fine for me:

package com.function;

import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.blob.*;

public class HttpTriggerJava {
    @FunctionName("HttpTriggerJava")
    public HttpResponseMessage run(@HttpTrigger(name = "req", methods = { HttpMethod.GET,
            HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        try {
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(
                    "{your storage connections tring}");
            CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
            CloudBlobContainer container = blobClient.getContainerReference("{container name}");
            CloudBlockBlob blob = container.getBlockBlobReference("{filename}");

            byte[] content = new byte[blob.getStreamWriteSizeInBytes()];
            blob.downloadToByteArray(content, 0);

            return request.createResponseBuilder(HttpStatus.OK)
                .body(content)
                .build();

        } catch (InvalidKeyException | URISyntaxException e) {
            e.printStackTrace();
            return request.createResponseBuilder(HttpStatus.NOT_FOUND)
                .body(e.getMessage())
                .build();
        } catch (StorageException e) {
            e.printStackTrace();
            return request.createResponseBuilder(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(e.getMessage())
                .build();
        }   
    }
}

Upvotes: 1

Related Questions