Springboot 上传文件到阿里云 OSS

项目目录Springboot 上传文件到阿里云 OSS

一、导入依赖

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

二、配置阿里云

resources目录下新建配置文件oss-conf.properties

# 阿里云配置
# 配置自己的accessKeyId
aliyun.access-key-id=xxxx
# 配置自己的accessKeySecret
aliyun.access-key-secret=xxxx
aliyun.oss.endpoint=http://oss-cn-beijing.aliyuncs.com
# 配置自己的bucketName
aliyun.oss.bucket-name=xxxx
# 配置自己的url前缀
aliyun.oss.url-prefix=xxxxx

三、添加配置类

添加配置类 AliYunOssProperties 和 AliYunProperties

@Data
@ConfigurationProperties(prefix = "aliyun.oss")
@PropertySource(value = {"classpath:oss-conf.properties"}, encoding = "UTF-8")
public class AliYunOssProperties {
    private String endpoint;
    private String bucketName;
    private String urlPrefix;
}
@Data
@ConfigurationProperties(prefix = "aliyun")
@PropertySource(value = {"classpath:oss-conf.properties"}, encoding = "UTF-8")
public class AliYunProperties {
    /**
     * @Autowired
     * 可指定 aliYunOssProperties 优先加载
     */

    @Autowired
    AliYunOssProperties aliYunOssProperties;
    private String accessKeyId;
    private String accessKeySecret;

    /**
     * 新版
     * @return
     */

    @Bean
    public OSS ossClient() {
        // 设置超时机制和重试机制
        ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
        conf.setConnectionTimeout(5000);
        conf.setMaxErrorRetry(3);
        return new OSSClientBuilder().build(aliYunOssProperties.getEndpoint(), accessKeyId, accessKeySecret, conf);
    }
}

四、激活配置类

新建配置类 EnableConfig

@Configuration
@EnableConfigurationProperties({AliYunOssProperties.classAliYunProperties.class})
@EnableRetry
public class EnableConfig 
{
}

五、添加 OssService

添加 AliYunOssService 和 AliYunOssServiceImpl

public interface AliYunOssService {

    /**
     * 创建 bucket
     * @param bucketName
     * @return
     */

    String createBucketName(String bucketName);

    /**
     * 删除 bucket
     * @param bucketName
     */

    void deleteBucket(String bucketName);

    /**
     * 创建目录
     * @param bucketName
     * @param folder
     * @return
     */

    String createFolder(String bucketName, String folder);

    /**
     * 根据 key 删除文件
     * @param bucketName
     * @param folder
     * @param key
     */

    void deleteFile(String bucketName, String folder, String key);

    /**
     * 上传图片到 oss
     * @param file
     * @return
     */

    String uploadObjectOSS(MultipartFile file);
}
@Slf4j
@Service
@AllArgsConstructor
public class AliYunOssServiceImpl implements AliYunOssService {
    private final AliYunOssProperties ossProperties;
    private final OSS ossClient;

    @Override
    public String createBucketName(String bucketName) {
        // 存储空间
        final String bucketNames = bucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建存储空间
            Bucket bucket = ossClient.createBucket(bucketName);
            log.info("创建存储空间成功");
            return bucket.getName();
        }
        return bucketNames;
    }

    @Override
    public void deleteBucket(String bucketName) {
        ossClient.deleteBucket(bucketName);
        log.info("删除" + bucketName + "Bucket成功");
    }

    @Override
    public String createFolder(String bucketName, String folder) {
        // 文件夹名
        final String keySuffixWithSlash = folder;
        // 判断文件夹是否存在,不存在则创建
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            // 创建文件夹
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            log.info("创建文件夹成功");
            // 得到文件夹名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
            return fileDir;
        }
        return keySuffixWithSlash;
    }

    @Override
    public void deleteFile(String bucketName, String folder, String key) {
        ossClient.deleteObject(bucketName, folder.concat(key));
        log.info("删除" + bucketName + "下的文件" + folder.concat(key) + "成功");
        log.info("执行成功[删除图片]key:{}", key);
    }

    @Override
    public String uploadObjectOSS(MultipartFile file) {
        String resultStr = null;
        String storePath = getStorePath();
        createFolder(ossProperties.getBucketName(), storePath);
        try {
            String fileName = file.getOriginalFilename();
            Long fileSize = file.getSize();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getInputStream().available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma""no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            // 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 上传文件 (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(ossProperties.getBucketName(), storePath + fileName, file.getInputStream(), metadata);
            // 解析结果
            resultStr = storePath + fileName;
            log.info("唯一MD5数字签名:" + putResult.getETag());
            log.info("执行成功[上传图片]key:{}", resultStr);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        return ossProperties.getUrlPrefix().concat(resultStr);
    }

    /**
     * oss目录归档
     * @return
     */

    private String getStorePath() {
        String currentTime = DateUtil.getCurrentTime();
        String storePath;
        storePath = "images/" + currentTime.substring(04) + "/" + currentTime.substring(57)
                + "/" +currentTime.substring(810) + "/";
        return storePath;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     * @param fileName
     * @return
     */

    public String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".png".equalsIgnoreCase(fileExtension)) {
            return "image/png";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        // 默认返回类型
        return "";
    }
}

至此,就可以使用 AliYunOssService 来操作阿里云 OSS 了!!

六、测试

新建个 Controller 测试下

@Slf4j
@RequestMapping("file")
@RestController
@AllArgsConstructor
public class FileController {
    private final AliYunOssService OssService;
    private final AliYunOssProperties ossProperties;

    /**
     * 上传图片
     * @param request
     * @return
     * @throws Exception
     */

    @GetMapping("/uploadPic")
    public AppResp<String> uploadPic(HttpServletRequest request){
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        MultipartFile file = req.getFile("file");
        return AppResp.succeed(OssService.uploadObjectOSS(file));
    }

    /**
     * 删除图片 by key
     * @param picture
     * @return
     */

    @GetMapping("/deletePic")
    public AppResp<Boolean> deletePic(@RequestParam("picture") String picture) {
        String replace = picture.replace(ossProperties.getUrlPrefix(), "");
        OssService.deleteFile(ossProperties.getBucketName(), replace.substring(018), replace.substring(18));
        return AppResp.succeed(true);
    }

}

使用 Postman 调用上传文件的接口Springboot 上传文件到阿里云 OSS

上传成功,返回图片地址

看下 OSS 服务器,图片已经存在,目录按照日期(年/月/日)创建Springboot 上传文件到阿里云 OSS

来试一下删除图片,参数是去掉 url 前缀的全路径Springboot 上传文件到阿里云 OSS

返回 0,删除成功Springboot 上传文件到阿里云 OSS

Springboot 上传文件到阿里云 OSS


原文始发于微信公众号(连帆起航):Springboot 上传文件到阿里云 OSS

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/239283.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!