通过阿里OSS文件服务返回的URL获取文件流下载

我们都知道将文件上传到阿里的OSS文件服务上后,可以通过generatePresignedUrl(bucketName, key, expiration)方法获取该文件的防问路径,但是当我们知道该文件的访问路径该如何通过路径获取该文件的下载流呢?

  1、截取文件访问路径,只要该文件的名称。

  2、通过阿里API提供的getObject方法获取文件信息

@GetMapping("/downLoadImage")
    public void downLoadImage(String fileName, HttpServletResponse response) {
        if (StringUtils.isNotBlank(fileName)) {
            OSSObject ossObject = downLoadImage(fileName);
            if (ossObject != null) {
                InputStream inputStream = ossObject.getObjectContent();
                int buffer = 1024 * 10;
                byte data[] = new byte[buffer];
                try {
                    response.setContentType("application/octet-stream");
                    // 文件名可以任意指定
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));//将文件名转为ASCLL编码
                    int read;
                    while ((read = inputStream.read(data)) != -1) {
                        response.getOutputStream().write(data, 0, read);
                    }
                    response.getOutputStream().flush();
                    response.getOutputStream().close();
                    ossObject.close();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }




public OSSObject downLoadImage(String fileName) {

        OSSClient ossClient = getInstance();
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName, HttpMethod.GET);
        // 设置过期时间。
        request.setExpiration(expiration);
        // 生成签名URL(HTTP GET请求)。
        URL signedUrl = ossClient.generatePresignedUrl(request);
        // 使用签名URL发送请求。
        Map customHeaders = new HashMap();
        // 添加GetObject请求头。
        //customHeaders.put("Range", "bytes=100-1000");
        OSSObject object = ossClient.getObject(signedUrl, customHeaders);
        return object;
    }


    public static synchronized OSSClient getInstance() {
        OSSClient ossClient = connInstances.get("oss");
        if (ossClient == null) {
            synchronized (FileUploadServiceImpl.class) {
                if (ossClient == null) {
                    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                }
            }
        }
        return ossClient;
    }

 

转载于:https://www.cnblogs.com/Amaris-Lin/p/9849308.html

你可能感兴趣的:(通过阿里OSS文件服务返回的URL获取文件流下载)