Erlo

小白的springboot之路(十七)、阿里云OSS 的使用

时间:2020-09-16   阅读:18次   来源:博客园
页面报错
点赞

0-前言

  项目中,文件服务必不可少,常用的有各云服务商的OSS服务(如阿里云OSS,腾讯云OSS,七牛云)、自建(fastDFS、minio);

  推荐:如果用云服务的话,阿里云OSS很方便,如果自建的话,minio无疑是首选;

  这里我们来简单介绍阿里云OSS的使用,minio我们后面介绍;

1-实现

1-0、开通OSS,并获取到相关配置参数供程序使用

  首先开通阿里云OSS,创建bucket、创建AccessKey,几分钟就搞定了,不会的具体百度下;

1-1、添加依赖

        <!-- 1、集成阿里云OSS -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.6.0</version>
        </dependency>

 

1-2、添加配置

# 阿里云存储参数配置
aliyun:
  oss:
    endpoint: oss-cn-beijing.aliyunccnblogs.com
    accessKeyId: XXX
    accessKeySecret: xxx
    bucketName: ansonfile

 

1-3、添加工具类(里面细节可以自己相应修改完善)

package com.example.oss.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

#zs#*
 * 描述: 阿里云OSS工具类
 * 版权: Copyright (c) 2020
 * 公司: XXX
 * 作者: yanghj
 * 版本: 4.0
 * 创建日期: 2020/9/16 11:38
 #fzs#
@Component
public class OssUtil
{
    //------------------变量----------
    protected static final Logger log = LoggerFactory.getLogger(OssUtil.class);

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    //文件存储目录
    private String filedir = "clouFile/";

    //-----------------对外功能----------------
    #zs#*
     * 1、单个文件上传
     * @param file
     * @return 返回完整URL地址
     #fzs#
    public String uploadFile(MultipartFile file)
    {
        String fileUrl = uploadImg2Oss(file);
        String str = getFileUrl(fileUrl);
        return  str.trim();
    }
    #zs#*
     * 1、单个文件上传(指定文件名(带后缀))
     * @param file
     * @return 返回完整URL地址
     #fzs#
    public String uploadFile(MultipartFile file,String fileName)
    {
        try
        {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, fileName);
            return fileName;
        }
        catch (Exception e)
        {
            return "上传失败";
        }
    }

    #zs#*
     * 2、多文件上传
     * @param fileList
     * @return 返回完整URL,逗号分隔
     #fzs#
    public String uploadFile(List<MultipartFile> fileList) {
        String  fileUrl = "";
        String  str = "";
        String  photoUrl = "";
        for(int i = 0;i< fileList.size();i++){
            fileUrl = uploadImg2Oss(fileList.get(i));
            str = getFileUrl(fileUrl);
            if(i == 0){
                photoUrl = str;
            }else {
                photoUrl += "," + str;
            }
        }
        return photoUrl.trim();
    }

    #zs#*
     * 3、通过文件名获取文完整件路径
     * @param fileUrl
     * @return 完整URL路径
     #fzs#
    public String getFileUrl(String fileUrl)
    {
        if (fileUrl !=null && fileUrl.length()>0) {
            String[] split = fileUrl.split("/");
            String url =  this.getUrl(this.filedir + split[split.length - 1]);
            return url;
        }
        return null;
    }


    //-----------内部辅助功能------------------------
    //获取去掉参数的完整路径
    private   String getShortUrl(String url)
    {
        String[] imgUrls = url.split("?");
        return imgUrls[0].trim();
    }
     // 获得url链接
    private String getUrl(String key) {
        // 设置URL过期时间为20年  3600l* 1000*24*365*20
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 20);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null)
        {
            return  getShortUrl(url.toString());
        }
        return null;
    }

    // 上传文件
    private String uploadImg2Oss(MultipartFile file)
    {
        //1、限制最大文件为20M
        if (file.getSize() > 1024 * 1024 *20)
        {
            return "图片太大";
        }
        //2、重命名文件
//        String originalFilename = file.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
//        Random random = new Random();
//        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); //文件后缀
        String uuid = UUID.randomUUID().toString();
        String name = uuid + suffix;

        try
        {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        }
        catch (Exception e)
        {
            return "上传失败";
        }
    }


     // 上传文件(指定文件名)

    private String uploadFile2OSS(InputStream instream, String fileName)
    {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    private 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";
        }
        //PDF
        if (FilenameExtension.equalsIgnoreCase(".pdf"))  {
            return "application/pdf";
        }
        return "image/jpeg";
    }

}

 

1-4、调用

controller:

#zs#*
 * 描述: OSS controller
 * 版权: Copyright (c) 2020
 * 公司: XXX
 * 作者: yanghj
 * 版本: 4.0
 * 创建日期: 2020/9/16 10:33
 #fzs#
@RestController
@RequestMapping("oss")
@Api(value = "OSS",tags = "OSS上传接口")
public class OssController
{

    @Autowired
    private OssUtil ossUtil;  //1、注入OssUtil


    @PostMapping("/uploadfile")
    @ApiOperation(value = "上传", notes = "上传")
    public Object fileUpload(@RequestParam MultipartFile file)
    {
        try
        {

            String url = ossUtil.uploadFile(file); //2、调用

            Map<String, Object> returnbody = new HashMap<>();
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.put("url", url);
            returnbody.put("data",returnMap);
            returnbody.put("code","200");
            returnbody.put("message","上传成功");
            return returnbody;
        }
        catch (Exception e)
        {
            Map<String, Object> returnbody = new HashMap<>();
            returnbody.put("data",null);
            returnbody.put("code","400");
            returnbody.put("message","上传失败");
            return  returnbody;
        }

    }

}

 

运行结果:

运行,可用阿里云提供的 OSS Browser直接看到结果;

 

2、总结

  阿里云OSS使用简单方便,官方提供的OSS Browser工具也很方便,按流量计费,费用也还不算贵,如果数据量也不是那么大,费用可接受,采用它无疑是最方便的;当然,如果不想付费使用,用minio自建文件服务也是很方便的,这个我们后面来说;

 

相关推荐

提交留言

评论留言

还没有评论留言,赶紧来抢楼吧~~

吐槽小黑屋()

* 这里是“吐槽小黑屋”,所有人可看,只保留当天信息。

  • Erlo吐槽

    Erlo.vip2020-09-27 07:24:01Hello、欢迎使用吐槽小黑屋,这就是个吐槽的地方。
  • 返回顶部