I have an application written using Spray, and I have a page which has an <input type="file" name="foo">
form element that gets POSTed to /fileUpload
.
I have a Spray route set up to listen to the path /fileUpload
using this code:
path("fileUpload") {
get { ctx => {
val request: HttpRequest = ctx.request
//Process the file, somehow with request?
ctx.complete("File Uploaded")
}}
}
I can't figure out how to get the POST body and get a handle on the file, and I can't find any examples online.
It must be possible to receive a file and process it with Spray or even through simple Scala or Java, but I don't know how to do it.
Can anybody help?
Thanks!
I ended up using the code below. Wasn't too hard, but there really should have been a Spray sample available somewhere about this.
multipart/form-data
forms must always be used (instead of the traditionalapplication/x-www-form-urlencoded
) if binary uploads are involved. More details here.My requirements were:
Some questions:
It's in the essence of REST API design to treat the client as a "human" (in debugging, we are), giving meaningful error messages in case something is wrong with the message.
Ok, after trying to write a Spray Unmarshaller for multipart form data, I decided to just write a scala HttpServlet that would receive the form submission, and used Apache's FileUpload library to process the request:
To grab the posted (possibly binary) file, and stick it somewhere temporarily, I used this:
It's possible with Spray, although I haven't checked if streaming works properly. I fiddled a bit and got this working:
If you upload a plain text file to a service that has this code in it, it coughs the original text back up. I've got it running together with an ajax upload; it should also work with an old fashioned file upload form.
It seems to me that there must be an easier way to do this, particularly the deep nesting of the content is rather clunky. Let me know if you find a simplification.
UPDATE (thx akauppi):