springboot整合京东云OSS存取文件,图片

springboot整合京东云OSS存取文件,图片

上个项目中使用到了京东云的OSS服务,这里记录一下,方便今后使用!

整体目录结构

springboot整合京东云OSS存取文件,图片_第1张图片

导入pom文件

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.11.136</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.1</version>
</dependency>

配置properties

springboot整合京东云OSS存取文件,图片_第2张图片
id和secret是注册京东云之后会给的
京东云注册地址:

1.登录京东云

springboot整合京东云OSS存取文件,图片_第3张图片

2.进入控制台,选择Access key管理

springboot整合京东云OSS存取文件,图片_第4张图片

3.获取id和secret

springboot整合京东云OSS存取文件,图片_第5张图片

4.创建一个空间

1.进入到"对象存储"–“空间管理”

springboot整合京东云OSS存取文件,图片_第6张图片

2.创建空间

根据需求选择(根据个人情况而定,本人在这里测试使用,也不商用,所在就公有读写了)
springboot整合京东云OSS存取文件,图片_第7张图片

空间名称就是# oss的存储空间
jd.oss.bucketName=xxxxx

OSS存取操作

读取properties配置文件
springboot整合京东云OSS存取文件,图片_第8张图片

1.上传文件/图片

/**
     * 上传文件到京东云OSS
     * @param uploadFile
     */
    @PostMapping("/file/upload")
    public String upload(@RequestParam("file") MultipartFile uploadFile){

        String filePath = "";

        try {
            filePath = getFilePath(uploadFile.getOriginalFilename());
            // 将MultipartFile对象转换为File
            File file = File.createTempFile("tmp", null);
            uploadFile.transferTo(file);
            initS3().putObject(bucketName, filePath, file);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return filePath;
    }

2.下载文件/图片

/**
     * 从OSS上下载文件
     */
    @GetMapping("/file/download")
    public void downLoad(@RequestParam(value = "fileName", required=true) String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception{
    
    	response.reset();
    	// OSS上的服务有个桶,所以切割一下,拿到正确的文件名
        String name = fileName.split("/")[1];

        // 设置response的Header 获取浏览器名(IE/Chome/firefox)
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        // 火狐
        if (userAgent.contains("firefox")) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("UTF-8"), "ISO8859-1"));

            // IE浏览器
        } else if (StringUtils.contains(userAgent, "msie")
                || StringUtils.contains(userAgent, "trident")
                || StringUtils.contains(userAgent,"edge")
                || userAgent.contains("like gecko")) {
            name = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + name);

            // 谷歌
        }else if (userAgent.contains("chrome")) {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("UTF-8"), "ISO8859-1"));
        } else {
            URLEncoder.encode(name, "UTF-8");
        }

        response.setContentType("application/octet-stream");

        download(response.getOutputStream(), fileName);
    }
/**
     * 下载文件
     * @param outputStream
     * @param fileName
     * @throws Exception
     */
    private void download(ServletOutputStream outputStream, String fileName) throws Exception {

        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        S3Object s3Object = initS3().getObject(bucketName, fileName);
        // 读取文件内容。
        BufferedInputStream in = new BufferedInputStream(s3Object.getObjectContent());
        BufferedOutputStream out = new BufferedOutputStream(outputStream);

        byte[] buffer = new byte[1024];
        int lenght = 0;
        while ((lenght = in.read(buffer)) > 0) {
            out.write(buffer, 0, lenght);
        }

        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }

3.删除文件/图片

/**
     * 删除OSS上的文件
     */
    @GetMapping("/file/delete")
    public void delete(@RequestParam("fileName") String fileName){
        initS3().deleteObject(bucketName, fileName);
    }

4.文件保存路径

此路径就是fileName.删除操作,下载都需要此fileName

/**
     * 文件保存的路径
     *
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String sourceFileName) {

        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(sourceFileName, type)) {

                return "image/" + getTime() + "." + StringUtils.substringAfterLast(sourceFileName, ".");
            }
        }

        return "file/" + getTime() + "." + StringUtils.substringAfterLast(sourceFileName, ".");
    }

5.时间转换格式

/**
     * 时间转换
     * @return
     */
    public String getTime(){
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = dateformat.format(new Date());

        return time;
    }

6.初始化OSS调用方法

private AmazonS3 initS3() {
        System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
        ClientConfiguration config = new ClientConfiguration();

        AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, accessKeySecret);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
        return s3;
    }

测试

1.上传

这里使用postman测试,post请求,key与Controller里的@RequestParam(“file”)
对应,选择file格式
springboot整合京东云OSS存取文件,图片_第9张图片
发送请求会返回一个fileName的路径,上传OK!可以在oss上看到
springboot整合京东云OSS存取文件,图片_第10张图片

在Object管理中查看
springboot整合京东云OSS存取文件,图片_第11张图片
在这里插入图片描述
这个就是刚才上传成功的文件

2.下载测试

springboot整合京东云OSS存取文件,图片_第12张图片
get请求,拼接的fileName就是刚才上传成功返回的(本人亲自炸的花生米,确实好吃.哈哈哈…)
还可以拼接外链访问,可以自行研究下

3.删除测试

没有做返回值,所以执行删除了看不出来.只能再执行次下载操作才可以看到效果
springboot整合京东云OSS存取文件,图片_第13张图片
其实已经删除了0.0
springboot整合京东云OSS存取文件,图片_第14张图片
控制台也给出提示了,不存在了,所以下载不了了
在这里插入图片描述

小结

其实引入一个新技术,就是几个流程:
1.引入pom/gradle
2.配置properties/yml
3.看情况写config
4.写一些xml
5.调用api
京东云OSS只用到了1,2,5 其实初始化那个可以写入到config里,注入方式来引入

=======================

欢迎大神指导,可以留言交流!

=============

本人原创文章,转载注明出入!

你可能感兴趣的:(京东云,java,云存储)