I'm new to this great framework and love its simplicity. Thanks a lot.
I would like to know how to stream a mp3 file from a RestController as described below. Unfortunately I can not see how to access a responsehelper to
access the output stream from the response. Or do I need to create a Serializer and convert the Bytes into a String (String str = new String(bytes);)
Any help is highly appreciated.
Example Code:
public void play() {
// Gets song id and retrieve file
String id = this.getId("song");
Song song = getSong(id);
File mp3 = new File(song.getLocation());
FileInputStream is = new FileInputStream(mp3);
// Stream the file to the response
OutputStream os = response.getOutputStream();
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition","attachment; filename=song.mp3");
response.setContentLength((int) mp3.length());
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
try {
while ((readBytes = buf.read()) != -1) os.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (os != null)
os.close();
if (buf != null)
buf.close();
}
}