精华内容
下载资源
问答
  • aliyun oss 操作

    2021-06-30 21:33:53
    获得endpoint ,开发环境使用外网访问,部署到aliyun的时候 使用 内网 地址 accessKeyId、accessKeySecret 创建accessKeyId、accessKeySecret 根据提示进行操作,官方不建议使用主账号设置 acce..

    目录

    oss控制台

    bucket

    endpoint

    accessKeyId、accessKeySecret

    oss帮助文档

    oss java sdk

    aliyun文档

    代码实现

    1. pom依赖

    2. controller

    3. 操作工具类

    4. properitity配置项获取

    5。 配置内容


    oss控制台

    https://oss.console.aliyun.com/

    可以自己申请一个账号进行一下操作,或者使用公司的测试账号进行测试

    bucket

    创建bucket,不能出现大写

    endpoint

    获得 endpoint ,开发环境使用外网访问,部署到aliyun的时候 使用 内网 地址

    accessKeyId、accessKeySecret

    创建 accessKeyId、accessKeySecret

    根据提示进行操作,官方不建议使用主账号设置 accesskey ,我这里是自己的aliyun进行测试使用,直接使用主账号操作 

    oss帮助文档

    https://help.aliyun.com/document_detail/32008.html?spm=a2c4g.11186623.6.918.79247bf9tJhMqx

    oss java sdk

    https://github.com/aliyun/aliyun-oss-java-sdk/

    aliyun文档

    aliyun所有的帮助文档,可以通过关键字进行搜索

    https://help.aliyun.com/

    代码实现

    1. pom依赖

        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
            <spring-boot.version>2.2.12.RELEASE</spring-boot.version>
            <com-alibaba-cloud.version>2.2.0.RELEASE</com-alibaba-cloud.version>
        </properties>    
        <!-- spring boot 依赖 -->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.12.RELEASE</version>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
    
            <!-- aliyun oss start -->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-api</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>com.googlecode.javaewah</groupId>
                <artifactId>JavaEWAH</artifactId>
                <version>1.1.6</version>
            </dependency>
            <!-- aliyun oss end -->
    
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
            </dependency>
    
            
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
            <dependency>
                <groupId>commons-beanutils</groupId>
                <artifactId>commons-beanutils</artifactId>
                <version>1.9.4</version>
            </dependency>
    
            <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-jdk8</artifactId>
                <version>1.2.0.Final</version>
            </dependency>
            <dependency>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>1.2.0.Final</version>
            </dependency>
    
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-core</artifactId>
                <version>3.3.0</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.49</version>
            </dependency>
    
            <!-- web -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    
            <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
            <dependency>
                <groupId>io.netty</groupId>
                <artifactId>netty-all</artifactId>
                <version>4.1.65.Final</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.74</version>
            </dependency>
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
            </dependency>
    
            
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
            
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>4.5.7</version>
            </dependency>
    
        </dependencies>
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>Greenwich.SR2</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
                <dependency>
                    <groupId>com.alibaba.cloud</groupId>
                    <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                    <version>2.1.0.RELEASE</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>

    2. controller

    
    /**
     * Created by yangLongFei on 2021/7/1 09:57
     * Version: $
     * Description:
     */
    @RestController
    @RequestMapping("/oss")
    public class AliyunOSSController {
    
        @Autowired
        private OSSFileUtils ossFileUtils;
        @Autowired
        private AliyunOSSProperties aliyunOSSProperties;
    
        @PostMapping("/upLoadFile")
        public OSSFileDTO upLoadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
            File file = ossFileUtils.multipartFile2File(multipartFile);
            OSSFileDTO ossFileDTO = ossFileUtils.upLoadFile(file);
            return ossFileDTO;
        }
    
        @GetMapping("/downLoadFile")
        public void downLoadFile(@PathParam("fileAPUrl") String fileAPUrl, HttpServletResponse response) throws IOException {
    
            File file = null;
            FileInputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                // 下载oss文件
                file = ossFileUtils.downLoadFile(fileAPUrl);
                //读文件
    //            List<String> stringList = FileUtils.readLines(file, "UTF-8");
                inputStream = new FileInputStream(file);
                String[] split = fileAPUrl.split("/");
                // 下载
    //            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(split[split.length-1], "UTF-8"));
                // 预览
                response.setHeader("content-disposition", "inline;filename=" + URLEncoder.encode(split[split.length - 1], "UTF-8"));
                int length = 0;
                byte[] buffer = new byte[1024];
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
            } finally {
                inputStream.close();
                outputStream.close();
                file.deleteOnExit();
            }
        }
    
    
    
    }
    

    3. 操作工具类

    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.*;
    import com.googlecode.javaewah.EWAHCompressedBitmap;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.web.client.RestTemplateBuilder;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.*;
    import java.net.MalformedURLException;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    import static cn.hutool.core.date.DatePattern.PURE_DATE_PATTERN;
    
    /**
     * Created by yangLongFei on 2021/7/1 08:35
     * Version: $
     */
    @Component
    @Slf4j
    public class OSSFileUtils {
    
        @Autowired
        private RestTemplateBuilder builder;
    
        /**
         * oss文件配置
         */
        private final AliyunOSSProperties ossProperties;
    
        /**
         * oss客户端实例
         */
        private OSS ossClient;
    
        /**
         * 构造方法
         */
        public OSSFileUtils(AliyunOSSProperties ossProperties) {
            // oss初始化
            this.ossProperties = ossProperties;
            this.init();
        }
    
        private void init() {
            this.ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(),
                    ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    
            // 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
            // 链接地址是:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
            if (ossClient.doesBucketExist(ossProperties.getBucketName())) {
                System.out.println("您已经创建Bucket:" + ossProperties.getBucketName() + ".");
            } else {
                System.out.println("您的Bucket不存在,创建Bucket:" + ossProperties.getBucketName() + ".");
                // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
                // 链接地址是:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
                ossClient.createBucket(ossProperties.getBucketName());
            }
        }
    
        /**
         * 上传文件
         * Created by yangLongFei on 2021/7/1 08:40
         * Version: $
         */
        public OSSFileDTO upLoadFile(File file) {
            try {
                // 判断容器是否存在,不存在就创建
                if (!ossClient.doesBucketExist(ossProperties.getBucketName())) {
                    // 创建 bucket容器
                    ossClient.createBucket(ossProperties.getBucketName());
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(ossProperties.getBucketName());
                    //设置bucket为公共读
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    ossClient.createBucket(createBucketRequest);
                }
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PURE_DATE_PATTERN);
                String timeStr = simpleDateFormat.format(new Date());
                // 设置文件路径和名称
                String fileUrl = ossProperties.getFilePath() + "/" + timeStr + "/" + file.getName();
                // 设置文件权限(公开读)
                ossClient.setBucketAcl(ossProperties.getBucketName(), CannedAccessControlList.PublicRead);
                // 上传文件,单线程上传
    //            PutObjectResult result = ossClient.putObject(new PutObjectRequest(ossProperties.getBucketName(), fileUrl, file));
    
                // 多线程上传
                UploadFileRequest uploadFileRequest = new UploadFileRequest(ossProperties.getBucketName(), fileUrl);
                // The local file to upload---it must exist.
                uploadFileRequest.setUploadFile(file.getPath());
                // Sets the concurrent upload task number to 5.
                uploadFileRequest.setTaskNum(5);
                // Sets the part size to 1MB.
                uploadFileRequest.setPartSize(1024 * 1024 * 1);
                // Enables the checkpoint file. By default it's off.
                uploadFileRequest.setEnableCheckpoint(true);
                UploadFileResult result = ossClient.uploadFile(uploadFileRequest);
    
                if (result != null) {
                    System.out.println(result);
                    log.info("------OSS文件上传成功------" + fileUrl);
                    return new OSSFileDTO(
                            file.length(), //文件大小
                            fileUrl, //文件的绝对路径
                            ossProperties.getWebUrl() + "?fileAPUrl=" + fileUrl, //自定义文件的web访问地址
                            file.getName().substring(file.getName().lastIndexOf(".") + 1), //文件后缀
                            ossProperties.getBucketName(),//存储的bucket
                            file.getName(), //原文件名
                            ossProperties.getFilePath() + "/" + timeStr //存储的文件夹
                    );
                }
            } catch (OSSException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            } finally {
                file.deleteOnExit();
            }
            return null;
        }
    
    
        /**
         * Created by yangLongFei on 2021/7/1 15:45
         * Version: $
         */
        public File downLoadFile(String folder) {
            String[] split = folder.split("/");
            String fileName = split[split.length - 1];
            String[] fileType = fileName.split("\\.");
            try {
                // 创建临时文件
                File file = File.createTempFile(fileType[0], fileType[1]);
    
                // 多线程下载
                DownloadFileRequest downloadFileRequest = new DownloadFileRequest(ossProperties.getBucketName(), folder);
                // Sets the local file to download to , 下载的文件保存为本地文件
                downloadFileRequest.setDownloadFile(file.getPath());
                // Sets the concurrent task thread count 5. By default it's 1.
                downloadFileRequest.setTaskNum(5);
                // Sets the part size, by default it's 100K.
                downloadFileRequest.setPartSize(1024 * 1024 * 1);
                // Enable checkpoint. By default it's false.
                downloadFileRequest.setEnableCheckpoint(true);
                // 下载文件,到临时文件
                DownloadFileResult downloadResult = ossClient.downloadFile(downloadFileRequest);
    
                // 单线程下载,请求下载文件,将文件拷贝到临时文件
    //            this.ossClient.getObject(new GetObjectRequest(ossProperties.getBucketName(), folder), file);
                return file;
            } catch (OSSException e) {
                // OSS在查找不到某对象时,会抛出ErrorCode为“NoSuchKey”的OSSException,而不是返回null
                if (e.getErrorCode().contains("NoSuchKey")) {
                    log.warn("找不到OSS文件:{}", fileName);
                } else {
                    e.printStackTrace();
                }
            } catch (ClientException | IOException e) {
                log.error("读取ossObject失败:{},fileName:{}", e.getMessage(), folder);
                e.printStackTrace();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            return null;
        }
    
    }

    4. properitity配置项获取

    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    /**
     * Created by yangLongFei on 2021/6/30 21:47
     * Version: $
     * Description:
     */
    @Component
    @ConfigurationProperties(prefix = "aliyun.oss")
    @Data
    public class AliyunOSSProperties {
        /**
         * endpoint是访问OSS的域名。
         */
        private String endpoint;
        /**
         * accessKeyId和accessKeySecret是OSS的访问密钥,您可以在控制台上创建和查看
         */
        private String accessKeyId;
        private String accessKeySecret;
        /**
         * Bucket用来管理所存储Object的存储空间
         */
        private String bucketName;
        /**
         * bucket 内文件的存储路径
         */
        private String filePath;
    
        /**
         * 下载的文件地址
         */
        private String webUrl;
    
        /**
         * 访问aliyunOSS的地址
         * macday-bucket.oss-cn-hangzhou.aliyuncs.com/yang_zzu/fileTest/20210701/cb9c0ad0ca614fa780f1d85d2e3dd91c-8505308444078692876843755.jpeg
         * 规则:bucketName.endpoint
         */
        private String loadFileUrl;
    
    }

    5。 配置内容

    配置内容,修改为自己的内容

    aliyun:
      oss:
        endpoint: oss-cn-hangzhou.aliyuncs.com
        accessKeyId: LTAI5tPaBXZaNx9vN71eMw7P3i
        accessKeySecret: Zmy6kGvU81FeRJLNe84dkTNITTPAil1
        bucketName: macday-bucket
        filePath: yang_zzu/fileTest
        webUrl: http://127.0.0.1:8071/oss/downLoad #自己写的下载接口
        loadFileUrl: https://macday-bucket.oss-cn-hangzhou.aliyuncs.com # 规则:bucketName.endpoint

    展开全文
  • 目录一、对象存储 OSS二、使用方式三、开始使用1、maven依赖2、配置类:AliyunOssConfig3、yml配置4、工具类 AliyunOSSUtil5、OssController 一、对象存储 OSS 对象存储服务(Object Storage Service,OSS)是一种...

    一、对象存储 OSS

    对象存储服务(Object Storage Service,OSS)是一种海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本。

    官方学习:https://help.aliyun.com/product/31815.html

    二、使用方式

    1. 服务端上传
      这个就是文件经过后台上传,需要注意的是,在使用MultipartFile类时,最大默认1M。需要修改上传文件的大小限制。大文件不推荐这种方式上传。

    2. 服务端签名直传
      意思就是后端生成签名,返回到前端,前端通过签名直接上传到aliyun的oss上,这样可以保证秘钥不可见,提高上传操作的安全性与效率。
      可参考:https://help.aliyun.com/document_detail/31926.html
      这里后端可以设置对应的callback,当成功上传到oss后,oss将上传文件的信息回调给服务端,服务端可以根据回调的url去做后续处理。

    三、开始使用

    1、maven依赖

    首先安装aliyun oss的SDK。
    https://help.aliyun.com/document_detail/32009.html

    下面使用的maven依赖:

    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>3.10.2</version>
    </dependency>
    

    2、配置类:AliyunOssConfig

    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    
    import javax.annotation.PostConstruct;
    
    /**
     * @Description: AliyunOssConfig
     * @Author: qiuyu
     * @Date: 2021/11/17
     **/
    @Data
    @Slf4j
    @Configuration
    @ConfigurationProperties(prefix = "aliyun.oss")
    public class AliyunOssConfig {
    
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
        private String filePath;
    
        @PostConstruct
        public void init(){
            log.debug("oss: endpoint:{},accessKeyId:{},bucketName:{},filePath:{}", endpoint, accessKeyId, bucketName, filePath);
        }
    
    }
    

    3、yml配置

    这里注意下,如果是后端上传文件,需要配置spring.servlet.multipart
    否则在使用MultipartFile类时,最大默认1M。

    aliyun:
      oss:
        accessKeyId: L*****************
        accessKeySecret: s**************
        bucketName: bucketName
        endpoint: oss-cn-hangzhou.aliyuncs.com
        filePath: filePath
    spring:
      servlet:
        multipart:
          max-file-size: 500MB
          max-request-size: 500MB
    

    4、工具类 AliyunOSSUtil

    package com.tmzh.saas.sfds.oss.utils;
    
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClient;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.common.utils.BinaryUtil;
    import com.aliyun.oss.model.*;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.InputStream;
    import java.nio.charset.StandardCharsets;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    @Slf4j
    @Component
    public class AliyunOSSUtil {
    
        private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        private static final long EXPIRTATION_TIME = 60*1000;
        private static final long CONTENT_LENGTH_RANGE_MIN = 0;
        private static final long CONTENT_LENGTH_RANGE_MAX = 1024*1024*1000;
    
        @Autowired
        private AliyunOssConfig aliyunOssConfig;
    
        private OSS getOssClient() {
            return new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        }
    
        /**
         * @Description: 判断文件是否存在
         * @Author: qy
         * @param fileName: 例如:filePath/fileName
         **/
        public boolean isExistFile(String fileName) {
            OSSClient ossClient = (OSSClient) getOssClient();
            boolean isExist;
            try {
                isExist = ossClient.doesObjectExist(aliyunOssConfig.getBucketName(), fileName);
                log.info("oss判断文件:{} 是否存在:{}", fileName,isExist);
            } catch (Exception e) {
                log.error("oss判断文件存在性异常", e);
            } finally {
                ossClient.shutdown();
            }
            return isExist;
        }
    
        /**
         * 上传
         */
        public String upload(MultipartFile file) {
            OSSClient ossClient = (OSSClient) getOssClient();
            String fileName = file.getOriginalFilename();
            log.info("=========>OSS文件上传开始:" + fileName);
            String datePath = format.format(new Date());
            try {
                //容器不存在,就创建
                if (!ossClient.doesBucketExist(aliyunOssConfig.getBucketName())) {
                    ossClient.createBucket(aliyunOssConfig.getBucketName());
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(aliyunOssConfig.getBucketName());
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    ossClient.createBucket(createBucketRequest);
                }
                // 获取上传的文件的输入流
                InputStream inputStream = file.getInputStream();
    
                //在文件名称里面添加随机唯一值,使用UUID生成
                // String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                fileName = aliyunOssConfig.getFilePath() + "/" + datePath + "/" + fileName;
                // 如果需要上传时设置存储类型与访问权限
                PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssConfig.getBucketName(), fileName, inputStream);
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(RequestUtil.getContentType(fileName.substring(fileName.lastIndexOf("."))));
                putObjectRequest.setMetadata(metadata);
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                //设置权限 这里是公开读
                ossClient.setBucketAcl(aliyunOssConfig.getBucketName(), CannedAccessControlList.PublicRead);
                if (null != result) {
                    String url = "https://" + aliyunOssConfig.getBucketName() + "." + aliyunOssConfig.getEndpoint() + "/" + fileName;
                    log.info("==========>OSS文件上传成功,OSS地址:" + url);
                    return url;
                }
            } catch (Exception e) {
                log.error("oss上传异常", e);
            } finally {
                //关闭
                ossClient.shutdown();
            }
            return null;
        }
    
    
        /**
         * 删除
         */
        public boolean deleteFile(String fileName) {
            OSSClient ossClient = (OSSClient) getOssClient();
            log.info("=========>OSS文件删除开始");
            try {
                if (!ossClient.doesBucketExist(aliyunOssConfig.getBucketName())) {
                    log.error("Bucket不存在");
                }
                ossClient.deleteObject(aliyunOssConfig.getBucketName(), fileName);
                log.info("==============>Object删除成功:" + fileName);
                return true;
            } catch (Exception e) {
                log.error("oss删除异常", e);
            } finally {
                //关闭
                ossClient.shutdown();
            }
        }
    
    
        /**
         * @Description: 查询文件名列表
         * @Author: qy
         * @param filePath: bucket下的文件路径,例如: filePath/
         **/
        public List<String> getObjectList(String filePath) {
            OSSClient ossClient = (OSSClient) getOssClient();
            String datePath = format.format(new Date());
            List<String> listRe = new ArrayList<>();
            try {
                log.info("===========>查询文件名列表");
                ListObjectsRequest listObjectsRequest = new ListObjectsRequest(aliyunOssConfig.getBucketName());
                // listObjectsRequest.setPrefix(aliyunOssConfig.getFilePath() + "/" + datePath + "/");
                listObjectsRequest.setPrefix(filePath);
                ObjectListing list = ossClient.listObjects(listObjectsRequest);
                // OSSobjectSummary下包含目录下所有的文件,不包含子目录
                for (OSSObjectSummary objectSummary : list.getObjectSummaries()) {
                    listRe.add(objectSummary.getKey());
                }
                return listRe;
            } catch (Exception ex) {
                log.error("==========>查询列表失败", ex);
                return new ArrayList<>();
            }
        }
    
        /**
        * @Description: 获取OSS上传Token
        * @param fileName: aaa.txt
        **/
        public Map<String, String> getUploadToken(String fileName) {
            OSSClient ossClient = (OSSClient) getOssClient();
            String datePath = format.format(new Date());
            try{
                log.info("===========>获取uploadToken");
                String dir = aliyunOssConfig.getFilePath()+ "/" + datePath +"/";
                long currentTime = System.currentTimeMillis();
                String key = dir + fileName.split("\\.")[0] + "-" + currentTime + "." + fileName.split("\\.")[1];
                long expireEndTime = currentTime + EXPIRTATION_TIME;
                Date expiration = new Date(expireEndTime);
    
                PolicyConditions policyConds = new PolicyConditions();
                policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, CONTENT_LENGTH_RANGE_MIN, CONTENT_LENGTH_RANGE_MAX);
                policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
                String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
                byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
                String encodedPolicy = BinaryUtil.toBase64String(binaryData);
                String postSignature = ossClient.calculatePostSignature(postPolicy);
                //JSONObject jasonCallback = new JSONObject();
                //你的回调URL
                //jasonCallback.put("callbackUrl", String.format("%s/callback/imgUploadSuccess", apiDomain));
                //阿里云回调返回参数
                //jasonCallback.put("callbackBody", "id=" + id + "&filename=${object}&type=" + type + "&etag=${etag}&size=${size}&height=${imageInfo.height}&width=${imageInfo.width}&mimeType=${mimeType}");
                //asonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
                //String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
                Map<String, String> res = new HashMap<>();
                //res.put("callback", base64CallbackBody);
                res.put("key", key); //dir + fileName (上传Object的名称。)
                res.put("OSSAccessKeyId", aliyunOssConfig.getAccessKeyId());
                res.put("policy", encodedPolicy); //Policy规定了请求表单域的合法性。
                res.put("signature", postSignature); //根据AccessKey Secret和Policy计算的签名信息,OSS验证该签名信息从而验证该Post请求的合法性。
                res.put("dir", dir); //前缀
                res.put("uploadUrl", "https://" + aliyunOssConfig.getBucketName() + "." + aliyunOssConfig.getEndpoint()); // "https://" + bucketname + '.' + endpoint;  (前端请求oss服务路径)
                res.put("expire", String.valueOf(expireEndTime / 1000));
                res.put("success_action_status", "200");
                log.debug("res:{}",res);
                return res;
            }
            catch (Exception e){
                log.error("==========>获取uploadToken失败", e);
            }
            finally {
                ossClient.shutdown();
            }
            return null;
        }
    
    }
    
    

    5、OssController

    @RestController
    @Api(tags = "OSS模块")
    @RequestMapping("/oss/file")
    public class OssController extends BaseController{
    
        @Autowired
        private AliyunOSSUtil aliyunOSSUtil;
    
    
        @PostMapping("/upload")
        @ApiOperation(value = "上传")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "form", dataType = "MultipartFile", dataTypeClass = MultipartFile.class, name = "file",
                        value = "文件", required = true)})
        public ResponseEntity<Result> upload(@RequestParam("file") MultipartFile multipartFile) {
            return ok(aliyunOSSUtil.upload(multipartFile));
        }
    
        @GetMapping("/list")
        @ApiOperation(value = "文件列表")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "query", dataType = "String", dataTypeClass = String.class, name = "filePath",
                        value = "bucket下的文件路径,例如: filePath/", required = true)})
        public ResponseEntity<Result> list(@RequestParam("filePath") String filePath) {
            return ok(aliyunOSSUtil.getObjectList(filePath));
        }
    
        @GetMapping("/isExist")
        @ApiOperation(value = "判断文件是否存在")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "query", dataType = "String", dataTypeClass = String.class, name = "fileName",
                        value = "例如:filePath/fileName", required = true)})
        public ResponseEntity<Result> isExist(@RequestParam("fileName") String fileName) {
            return ok(aliyunOSSUtil.isExistFile(fileName));
        }
    
        @DeleteMapping("/delete")
        @ApiOperation(value = "删除文件")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "query", dataType = "String", dataTypeClass = String.class, name = "fileName",
                        value = "例如:filePath/fileName", required = true)})
        public ResponseEntity<Result> delete(@RequestParam("fileName") String fileName) {
            return ok(aliyunOSSUtil.deleteFile(fileName));
        }
    
        /**
        * @Description: 服务端签名直传
        **/
        @PostMapping("/uploadToken")
        @ApiOperation(value = "获取uploadToken")
        @ApiImplicitParams({
                @ApiImplicitParam(paramType = "form", dataType = "String", dataTypeClass = String.class, name = "fileName",
                        value = "文件名", required = true)})
        public ResponseEntity<Result> uploadToken(@RequestParam("fileName") String fileName) {
            return ok(aliyunOSSUtil.getUploadToken(fileName));
        }
    
    }
    
    展开全文
  • aliyun

    2021-11-24 16:00:03
    echo deb https://mirrors.aliyun.com/debian stable main contrib non-free > /etcapt/sources.list echo deb https://mirrors.aliyun.com/debian stable-updates main contrib non-free > /etcapt/sources....

    echo deb https://mirrors.aliyun.com/debian stable main contrib non-free > /etc/apt/sources.list

    echo deb https://mirrors.aliyun.com/debian stable-updates main contrib non-free >> /etc/apt/sources.list

     

    展开全文
  • 项目场景: 调用CRM系统的OSS服务,下载文件时候,出现了下面的异常: com.aliyun.oss.ClientException:UnknownHost... 经过DeBug排查,是在创建一个OSSClient对象的时候抛出的异常: AliOssCloudUtil ossClientUtil...

     项目场景:

    调用CRM系统的OSS服务,下载文件时候,出现了下面的异常:

    com.aliyun.oss.ClientException:UnknownHost...

    经过DeBug排查,是在创建一个OSSClient对象的时候抛出的异常:

    AliOssCloudUtil ossClientUtil = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    原因分析:

    该报错是域名解析失败造成的,需要检查下客户端指定的 endpoint 是否正确。可以尝试在服务器上 ping endpoint,来验证下域名解析是否正确。

    我的问题场景:

    我们的代码环境有4个,分别是:dev,sit,uat和release(生产),为了保证数据不直接对外,crm系统的oss服务只服务于内网,也就是uat环境,所以我在其他环境下无法 ping 通 endpoint ,就会出现上述异常。

    所以,小伙伴们再使用 oss 服务前,最好先 ping 一下 endpoint ,免得代码调试遇到麻烦。

    展开全文
  • maven aliyun mirror

    2020-12-18 22:42:25
    nexus-aliyun</id> <mirrorOf>*</mirrorOf> <name>Nexus aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> </mirror>
  • Aliyun OSS存储上传文件

    2021-03-04 09:22:17
    首先第一步也是必不可少的一步,引入aliyun的依赖: com.aliyun.oss aliyun-sdk-oss joda-time joda-time 然后在Application配置文件中配置相关的信息: #阿里云 oss服务 #不同的服务器,地址不同 aliyun:...
  • golang中的aliyunoss

    2021-01-22 21:33:25
    go get -u github.com/aliyun/aliyun-oss-go-sdk/oss oss相关术语 权限 https://help.aliyun.com/document_detail/100676.html?spm=a2c4g.11186623.6.639.c8974c7dsCQHx3 文件上传 import ( "fmt" ...
  • https://github.com/alphasnow/aliyun-oss-laravel https://packagist.org/packages/alphasnow/aliyun-oss-laravel 安装方法 如果您通过composer管理您的项目依赖,可以在你的项目根目录运行: $ composer ...
  • Aliyun 删除视频

    2021-03-04 09:24:38
    首先第一步也是必不可少的一步,引入aliyun的依赖: com.aliyun aliyun-java-sdk-core 4.5.1 com.aliyun aliyun-java-sdk-vod 2.15.11 com.google.code.gson gson 2.8.2 配置APPlication文件 #阿里云 oss服务 ...
  • UOS换aliyun

    2021-03-17 10:01:27
    root账户下:vi /etc/apt/sources.list随后对其内容进行修改: 将第二行的 deb [by-hash=force] ... 改为: deb [by-hash=force] https://mirrors.aliyun.com/debian stable main contrib non-free 随后apt
  • - Status code: 404 for https://mirrors.aliyun.com/docker-ce/linux/centos/3/x86_64/stable/repodata/repomd.xml 按照官方文档部署并使用Docker(Alibaba Cloud Linux 3) - 云服务器 ECS - 阿里云这个安装...
  • 失败原因:阿里并未将当前jar包开源...完成下载后解压进lib目录,找到aliyun-java-vod-upload-1.4.14.jar 将 jar 包复制到Maven的 bin 目录下 全选地址栏输入cmd,打开命令行界面 输入命令: mvn install:i...
  • intellij idea 报错 “java: 程序包com.aliyun.odps.udf不存在” 错误处理
  • Aliyun 上传视频

    2021-03-04 09:23:36
    首先第一步也是必不可少的一步,引入aliyun的依赖: com.aliyun aliyun-java-sdk-core 4.5.1 com.aliyun aliyun-java-sdk-vod 2.15.11 com.google.code.gson gson 2.8.2 配置APPlication文件 #阿里云 oss服务 ...
  • mirrors.aliyun.com 无法解析

    千次阅读 2021-07-13 14:12:35
    修改 /etc/resolv.conf 使用阿里巴巴提供的DNS域名解析 nameserver 223.5.5.5 nameserver 223.6.6.6
  • aliyun-sdk-vod-upload直接复制到maven仓库中去 方式2: 使用maven命令进行安装 mvn install:install-file -DgroupId=com.aliyun -DartifactId=aliyun-sdk-vod-upload -Dversion=1.4.11 -Dpackaging=jar -Dfile=...
  • Aliyun 开通OSS服务

    2021-03-04 09:17:31
    1、 打开官网进入阿里云的官网 https://www.aliyun.com/ 2、 点击登录或者注册 3、 实名认证 4、 选择OSS服务 5、 开通OSS服务 6、 创建Bucket 7、 Bucket各个属性配置 ![在这里插入图片描述]...
  • aliyun-sdk-vod-upload爆红的解决方式 由于这个jar包还没有开源所以要自己去阿里云官方链接下载jar包 https://help.aliyun.com/document_detail/51992.html?spm=a2c4g.11186623.6.1029.2dab6cecZfMGvO 操作步骤 1、...
  • https://maven.aliyun.com/nexus/content/repositories/jcenter
  • 背景:尚硅谷谷粒学院项目中,视频点播上传文件的jar包开源,需要手动添加到仓库 ...mvn install:install-file -DgroupId=com.aliyun -DartifactId=aliyun-sdk-vod-upload -Dversion=1.4.11 -Dpac
  • Failed to fetch http://mirrors.aliyun.com/debian/dists/wheezy/InRelease Temporary failure resolving ‘mirrors.aliyun.com’ 在进行安装vim的时候输入命令apt-get update结果报错 Failed to fetch ...
  • 错误:1 http://mirrors.aliyun.com/ubuntu bionic InRelease 403 Forbidden [IP: 183.195.234.191 80] 错误:2 http://mirrors.aliyun.com/ubuntu bionic-updates InRelease 403 Forbidden [IP: 183.195.234.191 80...
  • 请求OSS重新UnknownHost报错如何排查 Causedby:java.net.UnknownHost 该报错是域名解析失败,请检查下客户端指定的endpoint是否正确,尝试pingbucket域名测试下解析是否正常,来验证下域名解析问题
  • 无法导入import com.aliyun.oss.OSSClientBuilder 在项目中无法导入import com.aliyun.oss.OSSClientBuilder; 是因为依赖版本太低了 ...aliyun-sdk-oss</artifactId> <version>3.10.2</ve
  • 相信大家在做尚硅谷的在线教育项目的时候,都会遇到的一个问题,aliyun-sdk-vod-upload在maven中一直报错,即使下载了老师的仓库一样没有解决,其实这个问题主要的引起原因是这个相关依赖并不是开源的,需要我们自己...
  • 本来我想下载阿里镜像站的centos7版本的镜像,因为我自己配置的本地源中没有ansible的安装包,但是再下载中遇到如下报错 方法一: 当时我搜索了很多都说是dns解析的问题:需要到/etc/reslove.conf文件中增加两句 ...
  • aliyun-oss-spring-boot-starter导入依赖报错unknown。 最后在官方aliyun-spring-boot的issues里找到了答案。 https://github.com/alibaba/aliyun-spring-boot/issues/40 pom.xml <dependency> <...
  • https://help.aliyun.com/document_detail/51992.html?spm=a2c4g.11186623.6.1029.2dab6cecZfMGvO#title-mbq-hhb-gy2 解压后进入lib目录 使用cmd进入lib目录,执行命令(版本号需要根据下载版本进行相应变更...
  • 因为aliyun-sdk-vod-upload-1.4.11.jar包还未正式开源,所以需要自己手动安装。首先,去阿里云官网下载demo例子,里面有jar包 ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 239,973
精华内容 95,989
关键字:

aliyun

友情链接: 时间.rar