Best practice to receive binary data

92 views
Skip to first unread message

Ori S

unread,
Nov 21, 2015, 7:05:00 PM11/21/15
to RestExpress
Hi all.

I'm working on a REST API and arrived now to the point where I need to receive binary uploads (request), like images. The response will be JSON.

Is there a best practice of how this should be done in RestExpress?
Do I need a serializer to parse incoming data or Netty/RestExpress does that for me?

An example would be very welcome, thanks in advance.

/OS

Ori S

unread,
Dec 1, 2015, 6:54:14 AM12/1/15
to RestExpress
I'll be replying to my own question in favor of anyone wondering the same. It was straightforward.

// The request's input stream.
InputStream is = null;


// The output stream to save uploaded data.
OutputStream os = null;


try {
 
// Get the upload as a binary file.
 
is = request.getBodyAsStream();
 
if(null == is) {
   
throw new BadRequestException("Request data is invalid");
 
}


 
// Save to output stream.
  os
= new BufferedOutputStream(new FileOutputStream(file));


 
byte[] buffer = new byte[8192];
 
int readBytes;
 
while(-1 != (readBytes = is.read(buffer))) {
   
if(0 < readBytes) {
      os
.write(buffer, 0, readBytes);
   
}
 
}
} finally {
 
if(null != is) {
   
try { is.close(); } catch(Exception ignored) { }
   
is = null;
 
}
 
if(null != os) {
   
try { os.close(); } catch(Exception ignored) { }
    os
= null;
 
}
}

/OS


Todd Fredrich

unread,
Dec 1, 2015, 5:35:55 PM12/1/15
to RestExpress
Awesome! Thanks for your contribution!

--Todd
Reply all
Reply to author
Forward
0 new messages