java文件下载

 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;

//方法1
 public ResponseEntity<byte[]> fileDownload() throws IOException {
        //读取源文件
        File file = new File("e://hello.txt");

        InputStream is = new FileInputStream(file);
        byte[] dest = null;
        int fileLength = is.available();
        dest = new byte[fileLength];
        is.read(dest);
        //创建http头并设置指定值
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attchement;filename=" + new String(file.getName().getBytes(), "ISO8859-1"));
        headers.add("application/octet-stream;","charset=utf-8");
        //设置HTTP响应状态。
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(dest,headers,statusCode);

        return responseEntity;
 }

//方法2
public HttpServletResponse fileDownload(String path, HttpServletResponse response) {
        InputStream in = null;
        OutputStream toClient = null;
        try {
            //path是指欲下载的文件的路径。
            File file = new File(path);
            //取得文件名。
            String filename = file.getName();
            //清空response
            response.reset();
            //设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //以流的形式下载文件。
            in = new BufferedInputStream(new FileInputStream(path));
            //文件缓冲区
            int b;
            byte[] by = new byte[1024];
            while ((b = in.read(by)) != -1) {
                toClient.write(by, 0, b);
            }
            toClient.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(toClient!=null){
                try {
                    toClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值