Reputation: 537
Brief Story: I have a Servlet which receives a request (getContentType() = audio/x-wav) that I can't read. I need to read this wave and save it on the server side.
Detailed Story: I know nothing about Flex, javascript, PHP and Python, I want to record (from the client side "Browser") a wave file and send it to the server to save it (for further ASR processing).
After some searching I found a library called Wami-Recorder (uses flex and java scrip) which I already used, but it didn't give me any java server side example, it also lacks the documentation so I decided to get my hands dirty to get it working. it contains a server side python and PHP example (I will list the PHP one):
<?php
# Save the audio to a URL-accessible directory for playback.
parse_str($_SERVER['QUERY_STRING'], $params);
$name = isset($params['name']) ? $params['name'] : 'output.wav';
$content = file_get_contents('php://input');
$fh = fopen($name, 'w') or die("can't open file");
fwrite($fh, $content);
fclose($fh);
?>
A final note is that I am sure if I created a socket server and directed the request to it, I will be able to get the media easily, but I want everything to be handled by the Servlets.
Upvotes: 2
Views: 1633
Reputation: 1109715
Basically, the Java servlet equivalent of the following line of PHP, which is the key line in the code,
$content = file_get_contents('php://input');
is
InputStream input = request.getInputStream();
This returns basically the sole HTTP request body. You can write it to an arbitrary OutputStream
the usual Java way. For example, a new FileOutputStream("/some.wav")
.
You should only realize that the HTTP request body can be read only once and also that it would implicitly be parsed when you invoke any of the request.getParameterXxx()
methods. So if you're interested in the parameters in the request URI query string as well, then you should instead use
String queryString = request.getQueryString();
and parse it further yourself (i.e. split on &
, then split on =
, then URLDecode
the name and value).
Upvotes: 2