Java实现上传下载

一、上传

二、下载

 1 import java.io.BufferedInputStream;
 2 import java.io.BufferedOutputStream;
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
 7 import java.io.OutputStream;
 8 import java.net.URLEncoder;
 9 
10 import javax.servlet.http.HttpServletResponse;
11 
12 public class DownloadFileUtil {
13     /**
14      * 弹窗下载
15      * @param response
16      * @param filePath
17      *            文件所在路径
18      * @param fileName
19      *            文件名
20      */
21     public void downFile(HttpServletResponse response, String filePath,
22             String fileName) {
23         try {
24             String path = filePath + fileName;
25             File file = new File(path);
26             if (file.exists()) {
27                 InputStream ins = new FileInputStream(path);
28                 BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
29                 OutputStream outs = response.getOutputStream();// 获取文件输出IO流
30                 BufferedOutputStream bouts = new BufferedOutputStream(outs);
31                 response.setContentType("application/x-download");// 设置response内容的类型
32                 response.setHeader("Content-disposition","attachment;filename="
33                                 + URLEncoder.encode(fileName, "GBK"));// 设置头部信息
34                 int bytesRead = 0;
35                 byte[] buffer = new byte[8192];
36                 // 开始向网络传输文件流
37                 while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
38                     bouts.write(buffer, 0, bytesRead);
39                 }
40                 bouts.flush();// 这里一定要调用flush()方法
41                 ins.close();
42                 bins.close();
43                 outs.close();
44                 bouts.close();
45             }
46         } catch (IOException e) {
47             e.printStackTrace();
48         }
49     }
50 }

 

有一篇不错的文章:http://blog.csdn.net/chow__zh/article/details/9288793#comments

转载于:https://www.cnblogs.com/zhaoyhBlog/p/6256128.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值