admin管理员组文章数量:1626405
有时候我们用户需要从服务器上下载文件,核实后就要有相应的服务来支持
下面为到家谢一个简单的服务器端的小例子,需要的朋友可以参考一下
代码很简单,注释也很全
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服务端代码 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1726114027a1055911.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论