所以这就是我的代码:
public class PdfDownloaderServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
httpServletResponse.setContentType("application/pdf");
ServletContext servletContext = httpServletRequest.getServletContext();
InputStream inputStream = servletContext.getResourceAsStream("/WEB-INF/classes/pdfs/x.pdf");
int read;
byte[] bytes = new byte[1024];
OutputStream os = httpServletResponse.getOutputStream();
while ((read = inputStream.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
它工作得很好。
但是,当我单击调用此方法的链接时,浏览器将打开该文件,但我希望浏览器直接下载该文件。我怎样才能做到这一点?
感谢。
答案 0 :(得分:1)
如果您希望浏览器作为附件下载,则需要使用Content-Disposition标头字段说明。请参阅http://greenbytes.de/tech/webdav/rfc6266.html#disposition.type,处置类型“附件”。