admin管理员组

文章数量:1535092

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

ossAPI

public class OSSTemplate {

    // endpoint以杭州为例,其它region请按实际情况填写
    String endpoint = "http://oss-cn-hangzhou.aliyuncs";
    // accessKey请登录https://ak-console.aliyun/#/查看
    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/download?filePaht=说明文档.doc";

本文标签: 阿里浏览器文件oss