Skip to content

Instantly share code, notes, and snippets.

@manxisuo
Last active December 16, 2015 17:19
Show Gist options
  • Save manxisuo/5469169 to your computer and use it in GitHub Desktop.
Save manxisuo/5469169 to your computer and use it in GitHub Desktop.
Servlet: 下载文件
/* 省略了package和import */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// 获取文件路径
String filePath = "/files/music/宁夏.mp3";
String realFilePath = this.getServletContext().getRealPath(filePath);
// 获取输入流
InputStream in = new BufferedInputStream(new FileInputStream(
realFilePath));
// 获取输出流
ServletOutputStream out = response.getOutputStream();
// 设置文件类型
response.setContentType("audio/mpeg");
// 设置浏览器处理文件的方式:attachment---保存文件;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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment