
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.IO流的方式下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public HttpServletResponse download(String path, HttpServletResponse response) {
try {
File file = new File(path);
String filename = file.getName();
String ext = filename.substring(filename.lastIndexOf( "." ) + 1).toUpperCase();
InputStream fis = new BufferedInputStream( new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader( "Content-Disposition" , "attachment;filename=" + new String(filename.getBytes()));
response.addHeader( "Content-Length" , "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType( "application/octet-stream" );
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
|
2.采用RequestDispatcher的方式进行
jsp页面中添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <%
response.setContentType( "application/x-download" );
String filedownload = "/要下载的文件名" ;
String filedisplay = "最终要显示给用户的保存文件名" ;
filenamedisplay = URLEncoder.encode(filedisplay, "UTF-8" );
response.addHeader( "Content-Disposition" , "attachment;filename=" + filedisplay);
try
{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if (dis!= null )
{
dis.forward(request,response);
}
response.flushBuffer();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
|
3.将文件下载到页面
注意:实际开发中绝大部分情况都是将文件存储在单独的服务器,但是 也会有一些小文件可以存放在项目中,此处存放在项目目录下,其实代码大同小异,几乎无差别。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <%
response.setContentType( "application/x-download" );
String filedownload = "/要下载的文件名" ;
String filedisplay = "最终要显示给用户的保存文件名" ;
filenamedisplay = URLEncoder.encode(filedisplay, "UTF-8" );
response.addHeader( "Content-Disposition" , "attachment;filename=" + filedisplay);
try
{
RequestDispatcher dis = application.getRequestDispatcher(filedownload);
if (dis!= null )
{
dis.forward(request,response);
}
response.flushBuffer();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
}
%>
|
以上就是在java中下载文件的三种方法,有这类需求的小伙伴,可以试着用java的知识来对文件的下载进行操作。看完本篇文章后,就可以运行代码试试成果了。更多Java学习指路:java下载