Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Framework: How to implement REST API for File Upload

I'm developing a REST API with Play 2 and I'm wondering how to implement file upload functionality.

I've read the official Play documentation but it just provides a multipart/form-data example, while my backend does not provide any form... it just consists of a REST API to be invoked by a JavaScript client or whatever else.

That said, what's the correct way to implement such an API? Should I implement a PartHandler and then still use the mutipartFormData parser? How should I pass the file content to the API? Is there any exhaustive example on this topic?

Any help would be really appreciated.

like image 464
j3d Avatar asked Dec 09 '25 03:12

j3d


1 Answers

To pass your contents, depending on your client side, you can encode the contents to Base64 at client side to pass the contents as Json (You can use Json body parser). Then on the server side you can decode the contents using a Base64 decoder (e.g. Apache Commons) to get the byte array. It will be as simple as

Base64.decodeBase64(YourEncodedFileContent)

When you have the byte array you can simply write it on disk or save it into database etc. We are using this approach in production and it works fine however we only handle small file uploads.

like image 111
centr Avatar answered Dec 11 '25 02:12

centr