阿里云oss的使用

1.pom

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

2.application.yml

# 阿里云oss
aliyun:
  oss:
    file:
      endpoint: # 域名 
      bucketname: # 桶
      accessKeyId: # accessKeyId
      accessKeySecret: # accessKeySecret

3.OssProperties.java

@Data
@Component
public class OssProperties implements InitializingBean {
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.file.bucketname}")
    private String bucketname;
    @Value("${aliyun.oss.file.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.file.accessKeySecret}")
    private String accessKeySecret;

    public static String ENDPOINT;
    public static String BUCKET_NAME;
    public static String ASSCESS_KEY_ID;
    public static String ASSCESS_KEY_SECRET;

    @Override
    public void afterPropertiesSet() throws Exception {
        ENDPOINT = endpoint;
        BUCKET_NAME = bucketname;
        ASSCESS_KEY_ID = accessKeyId;
        ASSCESS_KEY_SECRET = accessKeySecret;
    }
}

4.封装

@Slf4j
public class OssUtil {
    private static String endpoint = OssProperties.ENDPOINT;
    private static String accessKeyId = OssProperties.ASSCESS_KEY_ID;
    private static String accessKeySecret = OssProperties.ASSCESS_KEY_SECRET;
    private static String bucketName = OssProperties.BUCKET_NAME;
    private static OSSClient ossClient;

    /**
     * 上传文件到阿里云,并生成url
     * @param file
     * @return
     * @throws IOException
     */
    public static String UploadToAliyun(MultipartFile file) throws IOException {
        String path = new DateTime().toString("yyyy/MM/dd/");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String filedir = path + uuid +"."+suffix;
        log.info("------------>文件名称为:  " + filedir );

        InputStream is = file.getInputStream();
        ossClient  = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String url = "https://%s.%s/%s";;
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(is.available());
            objectMetadata.setCacheControl("no-cache");//设置Cache-Control请求头,表示用户指定的HTTP请求/回复链的缓存行为:不经过本地缓存
            objectMetadata.setHeader("Pragma", "no-cache");//设置页面不缓存
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            objectMetadata.setContentType(getcontentType(suffix));
            objectMetadata.setContentDisposition("inline;filename=" + filedir + "." + suffix);
            // 上传文件
            ossClient.putObject(bucketName, filedir, is, objectMetadata);
            url=String.format(url, bucketName, endpoint, filedir);
            log.info("图片地址为="+url);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("上传成功");
        }
        return url;
    }

    /**删除图片
     * @param key
     */
    public static void deletePicture(String key){
        ossClient  = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, key);
        ossClient.shutdown();
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     * @param suffix 文件后缀
     * @return String HTTP Content-type
     */
    public static String getcontentType(String suffix) {
        if (suffix.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        } else if (suffix.equalsIgnoreCase("gif")) {
            return "image/gif";
        }else if (suffix.equalsIgnoreCase("webp")) {
            return "image/webp";
        } else if (suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("jpg")) {
            return "image/jpeg";
        } else if (suffix.equalsIgnoreCase("png")) {
            return "image/png";
        } else if (suffix.equalsIgnoreCase("html")) {
            return "text/html";
        } else if (suffix.equalsIgnoreCase("txt")) {
            return "text/plain";
        } else if (suffix.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        } else if (suffix.equalsIgnoreCase("pptx") || suffix.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        } else if (suffix.equalsIgnoreCase("docx") || suffix.equalsIgnoreCase("doc")) {
            return "application/msword";
        } else if (suffix.equalsIgnoreCase("xml")) {
            return "text/xml";
        } else if (suffix.equalsIgnoreCase("mp3")) {
            return "audio/mp3";
        } else if (suffix.equalsIgnoreCase("amr")) {
            return "audio/amr";
        } else {
            return "text/plain";
        }
    }
}

5.使用

controller

public class FileController {

    @ApiOperation("单文件上传")
    @PostMapping("/upload")
    public ResultVo upload(
            MultipartFile file
    ) throws IOException {
        String url= OssUtil.UploadToAliyun(file);
        return ResultVo.ok().data("url",url);
    }

    @ApiOperation("多文件上传")
    @PostMapping(value = "/uploads")
    public  ResultVo fileS(MultipartFile[] files) throws  Exception{
        List<String> fileList=new ArrayList<>();
        for (MultipartFile file:files) { //用foreach处理list列表中的file
            fileList.add(OssUtil.UploadToAliyun(file));
        }
        return ResultVo.ok().data("fileList",fileList);//返回list
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小钱要努力

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值