oos 文件下载

前两篇写到了oos 上传 ,获取访问链接,那怎么下载呢。有两种方式
第一种使用文档里面的方法下载文件到本地,在读取文件下载给用户。第二种直接通过访问链接进行下载。

第一种下载方式

先写一个工具类将oos 的文件下载到本地具体代码如下

//key  为存储oos  的key  值  filename为下载后存储的路径
        public static void downloadFile(String key, String filename)
                throws OSSException, ClientException, IOException {  
            // 初始化OSSClient  
            OSSClient ossClient = new OSSClient(FilePath.endpoint, FilePath.accessKeyId,
                    FilePath.accessKeySecret);
            OSSObject object = ossClient.getObject(FilePath.bucketName, key);
            // 获取ObjectMeta  
            ObjectMetadata meta = object.getObjectMetadata();  

            // 获取Object的输入流  
            InputStream objectContent = object.getObjectContent();  
            ObjectMetadata objectData = ossClient.getObject(new GetObjectRequest(FilePath.bucketName, key),
                    new File(filename));  
            // 关闭数据流  
            objectContent.close();  

        }  

将文件下载到本能后读取文件流下载,代码如下:


    private void downFile(HttpServletResponse response,String Path) {
        try {    
            File file = new File(Path);
            if (file.exists()) {    
                InputStream ins = new FileInputStream(Path);
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面    
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
                BufferedOutputStream bouts = new BufferedOutputStream(outs);    
                response.setContentType("application/x-download");// 设置response内容的类型    
                response.setHeader(    
                        "Content-disposition",    
                        "attachment;filename="    
                                + URLEncoder.encode(Path, "UTF-8"));// 设置头部信息
                int bytesRead = 0;    
                byte[] buffer = new byte[8192];    
                // 开始向网络传输文件流    
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {    
                    bouts.write(buffer, 0, bytesRead);    
                }    
                bouts.flush();// 这里一定要调用flush()方法    
                ins.close();    
                bins.close();    
                outs.close();    
                bouts.close();    
            } else {    
                response.sendRedirect("../error.jsp");    
            }    
        } catch (IOException e) {    
            Log.error("文件下载出错", e);    
        }    
    }    

写一个js 用来发起下载请求。传送一个key 作为参数key 是什么请参考获取访问链接这篇文章。http://www.haha174.top/article/details/256945

$(".b_down").unbind("click").click(function(){
    var form=$("<form>");//定义一个form表单
    form.attr("style","display:none");
    form.attr("target","");
    form.attr("method","post");
    form.attr("action","/download/netfile.do");
    var fileInput=$("<input>");
    fileInput.attr("type","hidden");
    fileInput.attr("id","id");//设置属性的名字
    fileInput.attr("name","url");//设置属性的名字
    fileInput.attr("value","other/dbz_1505399510989.jpg");//设置属性的值
    $("body").append(form);//将表单放置在web中
    form.append(fileInput);
    form.submit();//表单提交
})

写一个controller进行测试


import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yuan.boot.util.BatchDownloadAction;

@RestController
@RequestMapping("/download")
public class DownLoadController {
    @RequestMapping("/netfile.do")
    public void DownLoadNet(String url,HttpServletResponse response) {
        new BatchDownloadAction().execute(response,url);
    } 
}

运行项目点击下载按钮出现如下图即成功实现了
这里写图片描述

第二种通过访问链接下载

首先先获取访问链接 具体的方法请参考http://www.haha174.top/article/details/256945
之后的到文件的输入流 然后 向网络传输文件流 完成下载具体工具类代码如下:


    //通过链接下载
    public void DownLoadLink(HttpServletResponse response, String  key) throws Exception {
        String urlStr=new OSSManageUtil().getUrl(key);//(key,path);
        System.out.println(urlStr);
        if(StringUtils.isNotBlank(urlStr)) {

            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //得到输入流
            InputStream inputStream;
            inputStream = conn.getInputStream();
           // InputStream ins = new FileInputStream(Path);
            BufferedInputStream bins = new BufferedInputStream(inputStream);// 放到缓冲流里面    
            OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
            BufferedOutputStream bouts = new BufferedOutputStream(outs);    
            response.setContentType("application/x-download");// 设置response内容的类型    
            response.setHeader(    
                    "Content-disposition",    
                    "attachment;filename="    
                            + URLEncoder.encode(key, "UTF-8"));// 设置头部信息
            int bytesRead = 0;    

            byte[] buffer = new byte[8192];    
            // 开始向网络传输文件流    
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {    
                bouts.write(buffer, 0, bytesRead);    
            }    
            bouts.flush();// 这里一定要调用flush()方法    
            inputStream.close();    
            bins.close();    
            outs.close();    
            bouts.close();    
        } else {    
            response.sendRedirect("../error.jsp");    
        }   
        //this.downFile(response,path);
    }

$(".b_down1").unbind("click").click(function(){
    var form=$("<form>");//定义一个form表单
    form.attr("style","display:none");
    form.attr("target","");
    form.attr("method","post");
    form.attr("action","/download/netfile.do");
    var fileInput=$("<input>");
    fileInput.attr("type","hidden");
    fileInput.attr("id","id");//设置属性的名字
    fileInput.attr("name","url");//设置属性的名字
    fileInput.attr("value","other/dbz_1505399510989.jpg");//设置属性的值
    $("body").append(form);//将表单放置在web中
    form.append(fileInput);
    form.submit();//表单提交
})

写一个controller进行测试




import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yuan.boot.util.BatchDownloadAction;

@RestController
@RequestMapping("/download")
public class DownLoadController {
    @RequestMapping("/netfile.do")
    public void DownLoadNet(String url,HttpServletResponse response) {
        new BatchDownloadAction().execute(response,url);
    } 

    @RequestMapping("/Linkfile.do")
    public void DownLoadLink(String url,HttpServletResponse response) throws Exception {
        new BatchDownloadAction().DownLoadLink(response,url);
    } 
}

这里写图片描述
出现此页面即成功
文章地址:http://www.haha174.top/article/details/251731
项目源码 https://github.com/haha174/day

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值