文件下载实现方法

来源:互联网 发布:淘宝外国儿童模特 编辑:程序博客网 时间:2024/06/07 05:27

文件下载实现方法

实现代码:

public void downLoadFile(){// 得到要下载文件的文件读取流InputStream is = null;// 定义文件输入流,用于下载文件OutputStream os = null;try {// 设置字符编码格式request.setCharacterEncoding("utf-8");// 下载路径String path = "D:\\test\\test.doc";//文件存放路径// 实例化出要下载文件File file = new File(path);is = new FileInputStream(file);os = response.getOutputStream();// 设置响应体属性String userAgent = request.getHeader("User-Agent");if (userAgent.indexOf("MSIE") >= 1)response.setHeader("Content-Disposition", "attachment;filename=\""+ java.net.URLEncoder.encode(file.getName(), "UTF-8") + "\"");elseresponse.addHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"), "iso-8859-1"));// 文件头属性设置response.addHeader("Content-length", file.length() + "");// 响应体内容设置response.setContentType("application/octet-stream");// 下载文件大小记数器int count = 0;// 实例化一个byte数组用于写入一次写入文件的大小byte[] buffer = new byte[1024 * 1024];// 如果读取文件成功while ((count = is.read(buffer)) != -1) {// 下载文件os.write(buffer, 0, count);}} catch (Exception e) {e.printStackTrace();} finally {try {if (is != null) {is.close();}if (os != null) {os.close();}} catch (IOException e) {e.printStackTrace();}}}
文件下载功能,接触了就会明白!

原创粉丝点击