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?

4
  • What error are you getting when you compile/run it? Have you researched how to convert data URI to File object? Commented Aug 30, 2018 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. Commented Aug 30, 2018 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 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: baeldung.com/java-write-to-file ) Commented Aug 30, 2018 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: stackoverflow.com/questions/23979842/… Commented Aug 31, 2018 at 10:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.