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