1

私はサーブレットが初めてで、Headfirst に従っています。MIME タイプが "application/jar" の jar ファイルをダウンロードする例があります。mp3ファイルをダウンロードするために「audio/mpeg3」に変更しました。ブラウザでプレーヤーを取得しましたが、再生されません。コードは次のとおりです。

public void doPost(HttpServletRequest req, HttpServletResponse resp) 
          throws ServletException, IOException

{
    resp.setContentType("audio/mpeg3");

    ServletContext ctx=this.getServletContext();
    InputStream is=ctx.getResourceAsStream("/RaOne.mp3");

    int read=0;
    byte[] bytes=new byte[1024];

    OutputStream os=resp.getOutputStream();
    while((read=is.read(bytes))!=-1)
    {
      os.write(bytes, 0, read);
    }

    os.flush();
    os.close();
  }

誰かが問題を解決するのを手伝ってくれますか?

4

1 に答える 1

6

あなたはこのようなものを試すことができます

ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
  stream = response.getOutputStream();
  File mp3 = new File("/myCollectionOfSongs" + "/" + fileName);

  //set response headers
  response.setContentType("audio/mpeg"); 

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

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

  FileInputStream input = new FileInputStream(mp3);
  buf = new BufferedInputStream(input);
  int readBytes = 0;
  //read from the file; write to the ServletOutputStream
  while ((readBytes = buf.read()) != -1)
    stream.write(readBytes);
} catch (IOException ioe) {
  throw new ServletException(ioe.getMessage());
} finally {
  if (stream != null)
    stream.close();
  if (buf != null)
    buf.close();
}
于 2012-09-17T07:24:13.297 に答える