您的位置:首页 > 编程语言 > Java开发

浏览器下载文件--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();
}
}
}

很简单的一个小例子
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: