为简单起见,下面代码只包含Servlet中的service方法。
- public void service(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException
- {
- // 获取文件路径
- String filePath = "/files/music/More Than I Can Say.mp3";
- String realFilePath = this.getServletContext().getRealPath(filePath);
- // 获取输入流
- InputStream in = new BufferedInputStream(new FileInputStream(
- realFilePath));
- // 获取输出流
- ServletOutputStream out = response.getOutputStream();
- // 设置文件类型
- response.setContentType("audio/mpeg");
- // 设置浏览器处理文件的方式:p_w_upload---保存文件;inline---在浏览器中在线打开。
- response.setHeader("Content-Disposition", "inline;filename=" + "a.mp3");
- // 缓冲区
- byte[] buf = new byte[1024];
- // 将从文件输入流获取的字节数据,写到响应的输出流
- while (-1 != in.read(buf))
- {
- out.write(buf);
- }
- // 关闭输入流和输出流
- in.close();
- out.close();
- }
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取文件路径 String filePath = "/files/music/More Than I Can Say.mp3"; String realFilePath = this.getServletContext().getRealPath(filePath); // 获取输入流 InputStream in = new BufferedInputStream(new FileInputStream( realFilePath)); // 获取输出流 ServletOutputStream out = response.getOutputStream(); // 设置文件类型 response.setContentType("audio/mpeg"); // 设置浏览器处理文件的方式:p_w_upload---保存文件;inline---在浏览器中在线打开。 response.setHeader("Content-Disposition", "inline;filename=" + "a.mp3"); // 缓冲区 byte[] buf = new byte[1024]; // 将从文件输入流获取的字节数据,写到响应的输出流 while (-1 != in.read(buf)) { out.write(buf); } // 关闭输入流和输出流 in.close(); out.close(); }