2

I recently created an HTTP Triggered Java Azure function to handle some of my backend tasks. This Azure-Functions main purpose was to accept/read in image files wrapped in a javascript FormData Object and upload the files to my azure blob storage.

I've been searching online but wasn't able to find a working example of how to read in a File from a FormData Object in java? I've seen some examples of this being done with azure functions in C# and node.js.

Here is the link --> Azure functions - How to read form data

So there has to be means of doing this in Java, does anyone have or can anyone provide a working example ?

public class Function {
     @FunctionName("HttpTrigger-Java")
     public HttpResponseMessage run(@HttpTrigger(name = "req", methods = 
  {HttpMethod.POST}) HttpRequestMessage<Optional<String>> request,
         final ExecutionContext context) {            

        String postRequest = request.getBody();

         //HELP: I need to get the FormData object from the postRequest some how... 
        FormData formDataObj = postRequest.getFormData();

        //HELP: Then I need to get my image file from the FormData Object...
        File sourceFile = formDataObj.getImageFile(); 


        try {
            // Parse the connection string 
            storageAccount = CloudStorageAccount.parse(storageConnectionString);

            // get blob client 
            blobClient = storageAccount.createCloudBlobClient();

            // get container name 
            container = blobClient.getContainerReference(containerName);    

            //Getting a blob reference
            blob = container.getBlockBlobReference(sourceFile.getName());

            //Creating blob and uploading file to it                
            blob.uploadFromFile(sourceFile.getAbsolutePath());

        } catch (StorageException ex) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("There was an error with Storage Account.").build();
        }

        return request.createResponseBuilder(HttpStatus.OK).body("Images Uploaded Successfully!, ").build();

}

}

vpandher
  • 31
  • 2
  • 5

1 Answers1

0

I believe you can parse the body using Apache Commons FileUpload and to do so from a string, this answer shows a way to do it.

PramodValavala
  • 6,026
  • 1
  • 11
  • 30
  • Hi thanks for replying! I've added my code in my question and added the term "HELP" at the exact place I need assistance. Would you be able to provide me a quick example ? The issue I'm having is that I am only given the **HttpRequestMessage** object and cant seem to find how to get the FormData object from that. – vpandher Mar 25 '20 at 00:50