Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Java servlet to send audio file

843841Oct 16 2007 — edited Oct 16 2007
Hi, I have used the example in this link http://www.java2s.com/Code/Java/Servlets/Sendmp3.htm to send a wav file to the client. I have changed the content type to audio/x-wav as I am sending a wav file not mp3 as in the example.

For some reason, it seems to send something back, but the audio file does not have any data in it (0 bytes). Eg try this link to see what happens: http://mel.our-lan.com/?=barcode50214561353872

The file browser opens up winamp/media player, but the file has no data in it. Can anybody see the problem in my code?:
String fileName = "";
				while (rs.next())
				{
					fileName = rs.getString("SoundClip");
				}
				
				if (fileName == null || fileName.equals(""))
					throw new ServletException(
					  "Invalid or non-existent file parameter in barcodeServlet.");

				String wavDir = ("http://mel.our-lan.com/wav-dir/" + fileName);
					
					/*getServletContext().getInitParameter("wav-dir");*/
				if (wavDir == null || wavDir.equals(""))
				  throw new ServletException(
					  "Invalid or non-existent wavDir context-param.");

				ServletOutputStream stream = null;
				BufferedInputStream buf = null;
				try
				{

					stream = response.getOutputStream();
					File wav = new File(wavDir + "/" + fileName);

					//set response headers
					response.setContentType("audio/x-wav");

					response.addHeader("Content-Disposition", "attachment; filename="
						+ fileName);

					response.setContentLength((int)wav.length());

					FileInputStream input = new FileInputStream(wav);

					byte[] buf1 = new byte[1024];
					int len;
					while ((len = input.read(buf1)) > 0)
						stream.write(buf1, 0, len);

					/* TRIED THE FOLLOWING ASWELL BUT SAME RESULT:
                                        buf = new BufferedInputStream(input);
					int readBytes = 0;
					//read from the file; write to the ServletOutputStream
					while ((readBytes = buf.read()) != -1)
						stream.write(readBytes);*/

					input.close();
				}
				catch (IOException ioe)
				{
					throw new ServletException(ioe.getMessage());
				}
				finally
				{
					if (stream != null)
						stream.close();
					if (buf != null)
						buf.close();
				}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 13 2007
Added on Oct 16 2007
2 comments
1,783 views