OSS对象存储从入门到使用

什么是OSS对象存储??

详细解释参考官方API

OSS对象存储主要使用于什么场景??

图片和音视频等应用的海量存储

OSS可用于图片、音视频、日志等海量文件的存储。各种终端设备、Web网站程序、移动应用可以直接向OSS写入或读取数据。OSS支持流式写入和文件写入两种方式。

猿校长

网页或者移动应用的静态和动态资源分离

利用BGP带宽,OSS可以实现超低延时的数据直接下载。OSS也可以配合阿里云CDN加速服务,为图片、音视频、移动应用的更新分发提供最佳体验。

猿校长

云端数据处理

上传文件到OSS后,可以配合媒体处理服务和图片处理服务进行云端的数据处理。

猿校长

主要使用步骤(以Springboot热部署为例):

  • 在pom.xml文件添加依赖
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>
  • 编写配置文件(以阿里云服务器的OSS对象存储为例),主要思想分两步走
    第一步:先创建客户端,配置endpoint,accessKeyId,accessKeySecret,bucketName,host,imgdir,filedir等详细信息
@Component
public class OSSClientUtil {

    protected static final Logger log = LoggerFactory.getLogger(OSSClientUtil.class);

    private String endpoint = "自己的endpoint";

    private String accessKeyId = "自己的accessKeyId";

    private String accessKeySecret = "自己的accessKeySecret";

    private String bucketName = "自己的bucketName";

    private String host = "自己的项目主机";

    //图片存储目录
    private String imgdir = "写啥随意/";
    //文件存储目录
    private String filedir = "写啥随意/";

    public void changeFiledir(String filedir) {
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    public String uploadImg2Oss(MultipartFile file) throws Exception {
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new Exception("上传图片大小不能超过10M");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            // TODO: 2020/6/2   update 
            InputStream inputStream =  file.getInputStream();
            this.uploadImg2Oss(inputStream, name);
            return name;
        } catch (Exception e) {
            log.info("文件目录为:"+ getUrl(bucketName));
            throw new Exception("上传失败...");
        }
    }

    /**
     * 上传图片获取fileurl
     * @param inputStream 输入流
     * @param fileurl 文件路径
     * @return 上传成功
     */
    private String uploadImg2Oss(InputStream inputStream, String fileurl) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma","no-cache");
            objectMetadata.setContentType(getcontentType(fileurl.substring(fileurl.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileurl);

            //上传文件
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            PutObjectResult putObjectResult = ossClient.putObject(bucketName,imgdir + fileurl,inputStream,objectMetadata);
            ret = putObjectResult.getETag();
        }catch (Exception e){
            log.error(e.getMessage(),e);

        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 获取文件路径
     * @param fileUrl 文件路径
     * @return
     */

    public String getImgUrl(String fileUrl) {
        if(StringUtils.isNotEmpty(fileUrl)){
            String[] split = fileUrl.split("/");
//            String url = this.getImgUrl(this.imgdir + split[split.length - 1]);
            String url = this.imgdir + split[split.length - 1];
            //log.info("该图片的路径为",url);
            return url;
        }
        return null;
    }

    /**
     * 删除文件
     * @param filename 文件名称
     */
    public void deleteFile(GenericRequest filename) {
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        String fileName = getFileName(filename);
        ossClient.deleteObject(bucketName,imgdir+fileName);
        ossClient.shutdown();
    }
    public static String getFileName(GenericRequest path){
        String fileName = new File(String.valueOf(path)).getName();
        //return fileName.substring(0, fileName.indexOf("?"));
        return fileName;
    }
    /**
     *生成url连接
     * @param key 
     * @return
     */
    public String getUrl(String key){

        //设置URL过期间为10年
        Date expiration = new Date(System.currentTimeMillis() + 3600*1000*24*365*10);
        //生成URL
        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName,key,expiration);
        if(url != null){
            return url.toString();
        }
        return null;
    }

    /**
     *
     * @param FilenameExtension 文件后缀格式
     * @return
     */

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
}

第二步:创建文件上传工具类

public class OssuploadUtil {
    public String updateHead(MultipartFile file) throws Exception {

        if (file == null || file.getSize() <= 0) {

            throw new Exception("file不能为空");
        }

        OSSClientUtil ossClient = new OSSClientUtil();

        String fileUrl = ossClient.uploadImg2Oss(file);

        String imgUrl = ossClient.getImgUrl(fileUrl);

        String[] split = imgUrl.split("\\?");

        return split[0];

    }

    /**

     * 上传图片到指定的文件夹


     * @param file

     * @param filedir

     * @return

     * @throws Exception

     */

    public String updateHead(MultipartFile file, String filedir) throws Exception {

        if (file == null || file.getSize() <= 0) {

            throw new Exception("file不能为空");

        }

        OSSClientUtil ossClient = new OSSClientUtil();

        ossClient.changeFiledir(filedir);

        String name = ossClient.uploadImg2Oss(file);

        String imgUrl = ossClient.getImgUrl(name);

        String[] split = imgUrl.split("\\?");

        return split[0];

    }
    /**

     * 上传多张图片,然后拼接所有的url

     *

     * @param image

     * @return

     */

    public Result uploadReturnUrl(List<String> image) {

        StringBuilder imageStr = new StringBuilder();

        for (int i = 0; i < image.size(); i++) {

            MultipartFile file = Base64tTransformUtil.base64ToMultipart(image.get(i));

            try {

                String url = this.updateHead(file);

                System.out.println("第" + (i + 1) + "张图片路径: " + url);

                if (i + 1 == image.size()) {

                    imageStr.append(url);

                } else {

                    imageStr.append(url + ",");

                }

            } catch (Exception e) {

                e.printStackTrace();

                return new Result().fail("图片上传失败!!!");

            }

        }

        return new Result().success(imageStr.toString(), "图片上传成功");

    }

    /**

     * 上传一张图片

     *

     * @param image

     * @return

     */

    public Result oneuploadReturnUrl(String image) {

        String url;

        MultipartFile file = Base64tTransformUtil.base64ToMultipart(image);

        try {

            url = this.updateHead(file);

            System.out.println("图片路径: " + url);

        } catch (Exception e) {

            e.printStackTrace();

            return new Result().fail("图片上传失败!!!");

        }

        return new Result().success(url, "图片上传成功");

    }



    /**

     * 上传一张图片到是定文件将夹

     *

     * @param image

     * @return

     */

    public Result oneuploadReturnUrlToPoint(String image, String filedir) {

        String url;

        MultipartFile file = Base64tTransformUtil.base64ToMultipart(image);

        try {

            url = this.updateHead(file, filedir);

            System.out.println("图片路径: " + url);

        } catch (Exception e) {

            e.printStackTrace();

            return new Result().fail("图片上传失败!!!");

        }

        return new Result().success(url, "图片上传成功");

    }

    /**

     *

     * @MethodName: deleteFile

     * @Description: 单文件删除

     * @param fileUrl 需要删除的文件url

     * @return boolean 是否删除成功

     */

    public boolean deleteFile(String fileUrl){

        OSSClientUtil ossClient = new OSSClientUtil();



        /**

         * 根据url获取bucketName

         */

        String bucketName = OssuploadUtil.getBucketName(fileUrl);

        /**

         * 根据url获取fileName

         */

        String fileName = OssuploadUtil.getFileName(fileUrl);

        if(bucketName==null||fileName==null) {

            return false;

        }

        try {

            GenericRequest request = new DeleteObjectsRequest(bucketName).withKey(fileName);

            ossClient.deleteFile(request);

        } catch (Exception oe) {

            oe.printStackTrace();

            return false;

        }

        return true;

    }



    /**

     *

     * @MethodName: getBucketName

     * @Description: 根据url获取bucketName

     * @param fileUrl 文件url

     * @return String bucketName

     */

    public static String getBucketName(String fileUrl){

        String http = "http://";

        String https = "https://";

        int httpIndex = fileUrl.indexOf(http);

        int httpsIndex = fileUrl.indexOf(https);

        int startIndex  = 0;

        if(httpIndex==-1){

            if(httpsIndex==-1){

                return null;

            }else{

                startIndex = httpsIndex+https.length();

            }

        }else{

            startIndex = httpIndex+http.length();

        }

        int endIndex = fileUrl.indexOf(".oss-");

        return fileUrl.substring(startIndex, endIndex);

    }



    /**

     *

     * @MethodName: getFileName

     * @Description: 根据url获取fileName

     * @param fileUrl 文件url

     * @return String fileName

     */

    public static String getFileName(String fileUrl){

        String str = "aliyuncs.com/";

        int beginIndex = fileUrl.indexOf(str);

        if(beginIndex==-1) {

            return null;

        }

        return fileUrl.substring(beginIndex+str.length());

    }

}
posted @ 2021-01-14 10:20  猿校长  阅读(771)  评论(0编辑  收藏  举报