浏览器下载阿里云OSS文件

浏览器下载文件在OSS存储,不需要将文件下载到本地,阿里云oss提供了相应api,返回文件的inputStream输入流

ossAPI

public class OSSTemplate {

    // endpoint以杭州为例,其它region请按实际情况填写
    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    // accessKey请登录https://ak-console.aliyun.com/#/查看
    String accessKeyId = "<yourAccessKeyId>";
    String accessKeySecret = "<yourAccessKeySecret>";
    String bucketName = "<yourBucketName>";
    // 创建OSSClient实例
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    public InputStream getFile(String filePath){
        OSSObject ossObject = ossClient.getObject(bucketName, filePath);
        InputStream in = ossObject.getObjectContent();
        return in;
    }
}

下载文件

public void getOSSFile(String filePath,HttpServletResponse response) {
            InputStream in = null;
            OutputStream out = null;
            try {
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
                response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));//文件名如果包含中文需要指定编码
                out = response.getOutputStream();
                in = getFile(filePath);
                byte[] data = new byte[1024];
                int len = 0;
                while ((len = in.read(data)) != -1) {
                    out.write(data, 0, len);
                }
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

浏览器下载

文件下载只支持get请求,而且不支持ajax,可以直接使用location

window.location.href = "http://example.com/download?filePaht=说明文档.doc";
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值