浏览器下载文件--Java服务端代码
2017-05-26 08:58
232 查看
有时候我们用户需要从服务器上下载文件,核实后就要有相应的服务来支持
下面为到家谢一个简单的服务器端的小例子,需要的朋友可以参考一下
代码很简单,注释也很全
public calss Download{
public void download(HttpServletResponse response){
try {
// path是指欲下载的文件的路径。
String path = "E://abc/a.html";
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
//设置文件名
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();
}
}
}
很简单的一个小例子
下面为到家谢一个简单的服务器端的小例子,需要的朋友可以参考一下
代码很简单,注释也很全
public calss Download{
public void download(HttpServletResponse response){
try {
// path是指欲下载的文件的路径。
String path = "E://abc/a.html";
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
//设置文件名
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();
}
}
}
很简单的一个小例子
相关文章推荐
- java 下载文件服务端代码
- 文件上传下载代码 java
- Java防止浏览器直接打开下载的文件
- HTML5拖拽文件到浏览器并实现文件上传下载功能代码
- java+jsp代码实现从FTP服务器上传下载文件
- java常用代码四(粘贴即用)---下载文件
- 防浏览器直接打开文件的java下载
- Java实现文件自动打包成zip并下载的代码
- 在浏览器中下载及打开文件的代码
- 通过java代码来下载FTP地址中带中文的文件
- Java文件下载代码
- JAVA连接FTP服务器,并上传/下载文件代码
- java防止浏览器直接打开下载的文件
- 通过Java代码打开浏览器,本地文件目录以及ftp站点
- 实现文件下载的java代码
- Java在编写文件下载的代码中如何避免文件名乱码情况
- Java FTP上传下载单个文件示例代码
- java下载文件在各个浏览器差异 以及中文乱码解决
- java 下载文件 兼容 ie 火狐 google 浏览器 ,解决下载文件乱码问题
- php 文件下载的相关代码 兼容所有浏览器