1

I am passing an image from a webpage using AJAX request. The image is passed as a Data URI to a Java function as shown below.

    public Result upload() {
    String dataUri = request().body().asText();
    System.out.println(dataUri);
    File file = dataUri;

    return ok("File uploaded");
}

The problem I am having is I think I need to convert the data URI to a file object in order to pass it into "File file = ". And if I can do that, then the image will be uploaded to the server. Any takers?

LorryBit
  • 11
  • 3
  • What error are you getting when you compile/run it? Have you researched how to convert data URI to File object? – pd12 Aug 30 '18 at 13:21
  • I've researched a lot but haven't found a solution that works yet, the error i get is "expected java.file.io" but got string or something like that. – LorryBit Aug 30 '18 at 13:34
  • I don't know what format your data is in, but since it's an image, I'm assuming it's base64. I just had a read of https://en.wikipedia.org/wiki/Data_URI_scheme and seems like you would need to pull out the base64 encoded binary using some string manipulation or data URI library, and decode to binary to write to a file. (1st google search for writing to File object in java: https://www.baeldung.com/java-write-to-file ) – pd12 Aug 30 '18 at 14:22
  • Cropped and uploaded! I found another link on stackoverflow that showed me how to convert base64 image to file. I have successfully loaded the cropped file to a directory on the server. Thanks for your help!! The link which has the answer is here: https://stackoverflow.com/questions/23979842/convert-base64-string-to-image/51372862#51372862 – LorryBit Aug 31 '18 at 10:34

1 Answers1

0

Cropped and uploaded! I found another link on stackoverflow that showed me how to convert base64 image to file. I have successfully loaded the cropped file to a directory on the server. Thanks for your help!! The link which has the answer is here: Convert base64 string to image

LorryBit
  • 11
  • 3