Reputation: 2522
I am writing a REST API using Restlet. I am mostly using a JSON as the body of all my POST requests, so a normal POST looks like this in my code:
@Post("json")
public Representation storeValue(String value){
JSONObject json = (JSONObject) JSONValue.parse(value);
String uname = (String)json.get("name");
...}
I get the JSON String from the request's body and parse it, do my stuff and return a response representation.
Here I want to do one more thing, I have a file (it's an xml, which I guess could be copy pasted inside a json key:value but I would rather avoid that) which has to be sent at the same time as the JSON. My idea is to request my api's users to send a multipart request, with the body as the normal JSON plus an attached file.
I am not too sure how I could do that, I found the FileUpload Restlet extension but very few complete examples of it so I'm not too sure how to use it.
In essence, question is how to retrieve a Body and a File from a Rest multipart request in Restlet 2+.
Sorry for being a bit vague, I am quite lost there.
Thank you in advance.
Upvotes: 0
Views: 1267
Reputation: 1084
You will need to add Exception handling but I have had success with, submitting a "multipart/form-data" Form :
@Put
public Representation uploadFile(final Representation representation){
List<FileItem> items = new RestletFileUpload(
new DiskFileItemFactory()).parseRepresentation(representation);
...
Which gives you a list items for the entry (or those) where isFormField() is false I can then access media type (from getContentType() as a String in the FileItem) and the Underlying InputStream as the file contents. You may be able to something fancier than accessing the Stream directly but that was all that I needed.
@Put vs @Post is a choice I leave to you
Upvotes: 1