栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

oss简单配置记录

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

oss简单配置记录

1.引用jar


    com.aliyun.oss
    aliyun-sdk-oss
    ${aliyun.oss.version}
l
在这里插入代码片

目录结构图:
(这是目录结构 图的url 是一个下载url 有时效 前端要是图片展示需要使用 l里面使用 标签)

2.引用配置


import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.Serializable;


@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssConfig implements Serializable {

    private String domain;
    @Value("${aliyun.oss.end-point}")
    private String endPoint;
    @Value("${aliyun.oss.access-keyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.access-key-secret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;
    @Value("${aliyun.oss.root-path}")
    private String rootPath;


}

在这里插入代码片

3.controller

package com.github.wxiaoqi.query.controller;

import com.github.wxiaoqi.query.service.AliyunOssService;
import com.github.wxiaoqi.security.api.dto.CommonReq;
import com.github.wxiaoqi.security.api.dto.activity.TDPointActivityDTO;
import com.github.wxiaoqi.security.api.dto.query.TBFileDTO;
import com.github.wxiaoqi.security.common.feign.guanaitong.GuanaitongFeign;
import com.github.wxiaoqi.security.common.feign.query.OssFeign;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



@RestController
@RequiredArgsConstructor
@RequestMapping("/query/aliyunOss")
public class AliyunOSSController implements OssFeign {


    @Autowired
    private AliyunOssService aliyunOssService;


    
    @PostMapping("/upload")
    private ObjectRestResponse upload(@RequestParam("file") MultipartFile  file) {
        return aliyunOssService.upload(file);
    }

    
    @PostMapping("/uploadFiles")
    private ObjectRestResponse uploadFiles(@RequestParam("files") MultipartFile[] files) {
        return aliyunOssService.uploadFiles(files);
    }

    
    @PostMapping("/uploadNull")
    private ObjectRestResponse upload() {
        return ObjectRestResponse.success();
    }

    @PostMapping("/delete")
    public ObjectRestResponse delete(@RequestBody CommonReq fileDTO   ) {
        return aliyunOssService.delete(fileDTO.getData());
    }

    
    @PostMapping("/getUrl")
    public ObjectRestResponse getUrl(@RequestParam("filePath") String filePath) {
        return aliyunOssService.getUrl(filePath);
    }

    /**
     * 删除文件
     *
     * @param fileDTO
     * @return
     */
public interface AliyunOssService {

    
    ObjectRestResponse upload(  MultipartFile file);

    ObjectRestResponse getUrl(String filePath);

    ObjectRestResponse uploadFiles(MultipartFile[] files);

    ObjectRestResponse delete(TBFileDTO fileDTO);
    /**
     * 删除文件
     * @param fileDTO
     * @return
     */
    protected String buildSavePath(String rootPath, String savePath) {
        //文件路径
        String path = DateUtil.format(new Date(), "yyyyMMdd");
        if(!StringUtils.isNullOrEmpty(rootPath)){
            path = rootPath + "/" + path;
        }
        if(savePath.startsWith("/")){
            return path + savePath;
        }else {
            return path + "/" + savePath;
        }
    }

    
    public abstract void createBucket(String bucketName);

    public abstract void deleteBucket(String bucketName);

    
    public abstract void deleteFile(String fileUrl);

    
    public abstract void deleteFile(List fileUrlList);

    
    public abstract boolean exist(String fileUrl);

    
    public abstract String upload(byte[] data, String savePath);

    
    public String upload(String fileUrl,String savePath){
        try {
            InputStream inputStream = new URL(fileUrl).openStream();
            return upload(inputStream, savePath);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    
    public abstract String upload(String name, MultipartFile files);

    
    public abstract String upload(InputStream inputStream, String savePath);
    
    
    public String upload(InputStream inputStream, String savePath, long size) {
        return upload(inputStream, savePath);
    }
}

在这里插入代码片

5.impl

package com.github.wxiaoqi.query.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.wxiaoqi.core.entity.query.TBFile;
import com.github.wxiaoqi.core.mapper.cropwx.TBPointUserMapper;
import com.github.wxiaoqi.core.mapper.query.TBFileMapper;
import com.github.wxiaoqi.query.service.AliyunOssService;
import com.github.wxiaoqi.security.api.dto.query.TBFileDTO;
import com.github.wxiaoqi.security.api.enums.FileType;
import com.github.wxiaoqi.security.common.context.baseContextHandler;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.msg.ResultCode;
import com.github.wxiaoqi.security.common.util.IdUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;


@Service
@AllArgsConstructor
@Slf4j
public class AliyunOssServiceImpl implements AliyunOssService {

    private final AliyunOssStorageService aliyunOssStorageService;

    @Autowired
    private TBFileMapper tbFileMapper;


    
    @Override
    public ObjectRestResponse upload(MultipartFile file) {
    // test/activity/14528169870204641281234.png  FileType.ACTIVITY_TYPE.getCode() 就是一个二级路径  activity
        String path = aliyunOssStorageService.upload(FileType.ACTIVITY_TYPE.getCode(), file);
        if (!StringUtils.isEmpty(path)) {
            TBFile seekerFile = new TBFile();
            seekerFile.setFileId(IdUtils.getSnowFlakeIdByDefault());
            seekerFile.setFileName(file.getOriginalFilename());
            seekerFile.setFileUrl(path);
            seekerFile.setCreateBy(baseContextHandler.getUserID());
            seekerFile.setCreateDateTime(LocalDateTime.now());
            seekerFile.setUpdateBy(baseContextHandler.getUserID());
            seekerFile.setUpdateDateTime(LocalDateTime.now());
            tbFileMapper.insert(seekerFile);
        }
        log.info("文件上传成功:{}", path);
        return ObjectRestResponse.success(path);
    }

    
    @Override
    public ObjectRestResponse uploadFiles(MultipartFile[] files) {
        //String url = aliyunOssStorageService.getUrl();
        ArrayList pathList = new ArrayList<>();
        log.info("多文件上传开始,文件数量:{}" + files.length);
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path = aliyunOssStorageService.upload(FileType.ACTIVITY_TYPE.getCode(), file);
                if (!StringUtils.isEmpty(path)) {
                    TBFile seekerFile = new TBFile();
                    seekerFile.setFileId(IdUtils.getSnowFlakeIdByDefault());
                    seekerFile.setFileName(file.getOriginalFilename());
                    seekerFile.setFileUrl(path);
                    seekerFile.setCreateBy(baseContextHandler.getUserID());
                    seekerFile.setCreateDateTime(LocalDateTime.now());
                    seekerFile.setUpdateBy(baseContextHandler.getUserID());
                    seekerFile.setUpdateDateTime(LocalDateTime.now());
                    tbFileMapper.insert(seekerFile);
                    pathList.add(path);
                }
            }
        }
        log.info("文件上传成功:{}", pathList);
        return ObjectRestResponse.success(pathList);
    }

    @Override
    public ObjectRestResponse delete(TBFileDTO fileDTO) {
        if (fileDTO.getFileUrl()==null){
            return ObjectRestResponse.error(ResultCode.REQUIRED_PARAM_NOT_FOUND);
        }
        aliyunOssStorageService.deleteFile(fileDTO.getFileUrl());
        TBFile tbFile = new TBFile();
        tbFile.setFileUrl(fileDTO.getFileUrl());
        int delete = tbFileMapper.delete(Wrappers.query(tbFile));
        return ObjectRestResponse.success();
    }


    @Override
    public ObjectRestResponse getUrl(String filePath) {
     //filePath的例子 test/activity/14528169870204641281234.png   
        String url = aliyunOssStorageService.getUrl(filePath);

        return ObjectRestResponse.success(url);
    }

    /**
     * 删除文件
     *
     * @param fileDTO
     * @return
     */
@Slf4j
@Service
public class AliyunOssStorageService extends CloudStorageService {

    private AliyunOssConfig config;

    public AliyunOssStorageService(AliyunOssConfig config) {
        this.config = config;
    }

    
    @Override
    public void createBucket(String bucketName) {
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        try {
            boolean exists = ossClient.doesBucketExist(bucketName);//判断存储空间是否存在
            if (exists) {
                return;
            }
            // 创建CreateBucketRequest对象。
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            // 创建存储空间。
            ossClient.createBucket(createBucketRequest);
        } catch (Exception e) {
            throw new RuntimeException("创建Bucket失败", e);
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }

    }

    public String getUrl(String filePath) {
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        try {
            // 指定签名URL过期时间为10分钟。
            Date expiration = new Date(new Date().getTime() +  1000 * 60 * 10);
            URL url = ossClient.generatePresignedUrl(config.getBucketName(), filePath, expiration);
            log.info("url:{} ,config.getBucketName():{} ", url.toString(), config.getBucketName());
            return url.toString();
        } catch (Exception e) {
            throw new RuntimeException("创建Bucket失败", e);
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }

    
    @Override
    public void deleteBucket(String bucketName) {
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        try {
            // 删除存储空间。
            ossClient.deleteBucket(bucketName);
        } catch (Exception e) {
            throw new RuntimeException("删除Bucket失败", e);
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }

    
    public String getSavePath(String fileUrl) {
        return fileUrl.substring(config.getDomain().length() + 1);
    }

    
    @Override
    public void deleteFile(String fileUrl) {
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        try {
            String savePath = fileUrl;//getSavePath(fileUrl);
            ossClient.deleteObject(config.getBucketName(), savePath);
        } catch (Exception e) {
            throw new RuntimeException("删除File失败", e);
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }

    
    @Override
    public void deleteFile(List fileUrlList) {
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        try {
            List keys = new ArrayList<>();
            fileUrlList.forEach(item -> keys.add(getSavePath(item)));
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(config.getBucketName()).withKeys(keys));
            List deletedObjects = deleteObjectsResult.getDeletedObjects();
        } catch (Exception e) {
            throw new RuntimeException("批量删除文件失败", e);
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }

    
    @Override
    public boolean exist(String fileUrl) {
        String objectName = getSavePath(fileUrl);
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        boolean exist = false;
        try {
            // 判断文件是否存在。doesObjectExist还有一个参数isOnlyInOSS,如果为true则忽略302重定向或镜像;如果为false,则考虑302重定向或镜像。
            exist = ossClient.doesObjectExist(config.getBucketName(), objectName);
        } catch (Exception e) {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
        //  返回是否存在
        return exist;
    }

    @Override
    public String upload(byte[] data, String savePath) {
        return upload(new ByteArrayInputStream(data), savePath);
    }

    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String upload(String name, MultipartFile file) {
        log.info("单文件上传开始:" + file.getOriginalFilename());

        // 创建OSSClient实例。
        OSS ossClient = getOSSClient();

        String savePath = config.getRootPath() + name + "/" + IdUtils.getSnowFlakeIdByDefault() + file.getOriginalFilename();
        // String savePath = config.getRootPath() + file.getOriginalFilename();
        try {
            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
            Objectmetadata metadata = new Objectmetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            metadata.setObjectAcl(CannedAccessControlList.Private);
            //上传文件到oss
            ossClient.putObject(config.getBucketName(), savePath, file.getInputStream(), metadata);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败,请检查配置信息", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return savePath;
    }

    
    public void downLoad(String fileName, String fileUrl, String savePath) {

        log.info("文件下载,开始,文件名:{},文件路径:{},下载至本地路径:{}", fileName, fileUrl, savePath);
        // 创建OSSClient实例。
        OSS ossClient = getOSSClient();

        //本地保存完整路径
        String localFileStr = savePath + "\" + fileName;

        // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
        // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        ossClient.getObject(new GetObjectRequest(config.getBucketName(), fileUrl), new File(localFileStr));

        log.info("下载结束,本地查看路径:{}", savePath);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    
    public void downLoad(String fileName, String fileUrl, String savePath, HttpServletResponse response) throws IOException {

        log.info("文件下载,开始,文件名:{},文件路径:{},下载至本地路径:{}", fileUrl);
        // 创建OSSClient实例。
        OSS ossClient = getOSSClient();

        //本地保存完整路径

        String url = "test/韩金龙1/181612872605_.pic.jpg";
        // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(config.getBucketName(), url);

//        String contentType = ossObject.getResponse().getHeaders().get("Content-Type");
//        String versionId = ossObject.getResponse().getHeaders().get("x-oss-version-id");
        InputStream inputStream = ossObject.getObjectContent();
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        inputStream.close();
        // 清空response
        response.reset();
        String filename = "韩金龙1-181612872605_.pic.jpg";
        response.setContentType("application/octet-stream;charset=UTF-8");
        String fileName2 = new String(filename.getBytes("gb2312"), "iso8859-1");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName2);
        OutputStream ouputStream = response.getOutputStream();
        ouputStream.write(buffer);
        ouputStream.flush();
        ouputStream.close();

        log.info("下载结束,本地查看路径:{}");
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public String upload(InputStream inputStream, String savePath) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(config.getEndPoint(), config.getAccessKeyId(), config.getAccessKeySecret());
        try {
            savePath = buildSavePath(config.getRootPath(), savePath);
            ossClient.putObject(config.getBucketName(), savePath, inputStream);
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败,请检查配置信息", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return config.getDomain() + "/" + savePath;//返回文件的访问URL地址
    }

    public OSS getOSSClient() {
        return new OSSClientBuilder().build(config.getEndPoint(), config.getAccessKeyId(), config.getAccessKeySecret());
    }

    public static void main(String[] args) throws IOException {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
//        String endpoint = "yourEndpoint";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
//        String accessKeyId = "yourAccessKeyId";
//        String accessKeySecret = "yourAccessKeySecret";

        String endPoint = "https://oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tG3GtEFaw21ibEXYsny";
        String accessKeySecret = "62VSUrXNlyqeQJAADncPXqXQTn2rFz";
        String bucketName = "nbt-zhaopin-pri-testbucket";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        // 依次填写Bucket名称(例如examplebucket)、Object完整路径(例如exampledir/exampleobject.txt)和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
//        String filePath = "D:\教育经历.png";
//        File file = new File(filePath);
//        String fileName = file.getName();
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, "exampledir/" + fileName, file);

        // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
//        Objectmetadata metadata = new Objectmetadata();
//        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
//        metadata.setObjectAcl(CannedAccessControlList.Private);
//        putObjectRequest.setmetadata(metadata);

        // 上传文件。
//        ossClient.putObject(putObjectRequest);


        // 判断文件是否存在。如果返回值为true,则文件存在,否则存储空间或者文件不存在。
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
//        boolean found = ossClient.doesObjectExist(bucketName, "exampledir/新建文本文档 (3).txt");
//        System.out.println(found);

        // 下载文件
//        ossClient.getObject(new GetObjectRequest(bucketName, "test/eladmin原日志文件.txt"), new File("D:\test\eladmin原日志文件.txt"));

        //流式下载

        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, "test/eladmin原日志文件.txt");

        // 读取文件内容。
        System.out.println("Object content:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        while (true) {
            String line = reader.readLine();
            if (line == null) break;

            System.out.println("n" + line);
        }
        // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
        reader.close();

        // 关闭OSSClient。
        ossClient.shutdown();
    }
}

6.配置yml

#阿里云OSS服务器
aliyun:
  oss:
    end-point: https://oss-cn-shanghai.aliyuncs.com
    access-keyId: LTAI5tBv3J1GcjJEo1kR6c8P
    access-key-secret: ZsIzEqGVnBIo7sZxs9fSgwlbmpuB93
    bucket-name: nbt-jifen-pub-testbucket
    root-path: test/
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351750.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号