1

I am building a servlet that accepts an image in a POST request. with each post there should be an associated ID. My question is how to pass these two distinct data values in a post, where one is a short string, and another is a large chunk of binary data.

I could have both as post parameters,

id=123
content=...megabytes of binary data...

but I need the flexibility of handling the content as a stream, as it could be quite large. I could also follow the above pattern by parsing the input myself as binary data, which I'd like to avoid. I guess I'd need to parse it character by character looking for the keys. ugly.

Am I missing the correct pattern for handling this?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
  • would adding id= parameter to the query string, then calling request.getQueryString() manually do the trick? – Jeffrey Blattman Feb 14 '11 at 18:40
  • 1
    IS there any issue in passing `id` as part of post data? And then getting it by `request.getParameter("id")`? – Nishant Feb 14 '11 at 18:40
  • Indeed. I don't understand the issue in this. Are you parsing the request body yourself or something? Rather delegate the tedious job to a 3rd party API like Apache Commons FileUpload. You can find [here](http://stackoverflow.com/questions/2422468/how-to-upload-files-in-jsp-servlet/2424824#2424824) an example. – BalusC Feb 14 '11 at 19:47
  • @nishant yes, there's a problem. the post data is large and i can't load it into memory, i need to deal with it as a stream. as soon as you say getParameter(), the entire stream is read, and parsed into memory. – Jeffrey Blattman Feb 15 '11 at 16:15

1 Answers1

2

The standard technique, used in browser to send form data containing both text and file inputs, is to use multi-part form data.

Apache commons FileUpdload could be used at server-side to parse the request, and give you access to the uploaded image as a stream.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • thanks. that is the more general solution. for my purposes, i ended up adding the "id" parameter as path info, which worked like a charm. – Jeffrey Blattman Feb 15 '11 at 16:16