赞
踩
平淡无奇,其实就是对应了在网址中输入url,浏览器就能直接下载文件:
- // 首先根据请求,找到服务器端文件存储地址,并创建File文件
- File file = new File(filePath);
-
- filename = new String(filePath.getBytes("iso8859-1"),"UTF-8");
-
- //设置响应头,控制浏览器下载该文件
- response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
-
- //读取要下载的文件,保存到文件输入流
- DataInputStream dataInputStream = new DataInputStream(new FileInputStream(file));
-
- //创建输出流
- out = response.getOutputStream();
-
- //缓存区
- byte bufferOut[] = new byte[1024];
- int bytes = 0;
-
- //循环将输入流中的内容读取到缓冲区中
- while ((bytes = dataInputStream.read(bufferOut)) != -1) {
- out.write(bufferOut, 0, bytes);
- }
-
- //关闭
- out.close();
上面极为关键的一步就是第二步,通过第二步,我们才能控制浏览器下载该文件。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。