阿里云图片文件上传

一,官网地址

复制代码
https://help.aliyun.com/document_detail/84781.html

一切依据于官网

二,导入依赖

复制代码
<dependencies>
    <!-- 阿里云oss依赖 -->
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
    </dependency>

    <!-- 日期工具栏依赖 -->
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>
</dependencies>

三,创建配置文件

复制代码
#服务端口
server.port=8205
#服务名
spring.application.name=service-oss

#环境设置:dev、test、prod
spring.profiles.active=dev
        
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=guli-file

四创建启动类

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;


@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan("com.atguigu")
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class,args);
    }
}

五,创建常量类

由于环境的不同,配置需要变化,因此需要将配置文件变为软编码而不是写在硬编码里面,耦合性较高

java 复制代码
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class ConstantPropertiesUtil implements InitializingBean {
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}

六,创建controller→service

java 复制代码
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "文件上传接口")
@RestController
@RequestMapping("/admin/oss/file")
public class OssController {
    @Autowired
    private OssService ossService;
    /**
     * @Description: 上传文件
     * @return:  文件的url
     * @param:文件流
     * @author: Mr zhan
     */
    @ApiOperation("上传图片到阿里云")
    @PostMapping("upload")
    public R upload(MultipartFile file) {
        //传递到service

      String fileUrl=ossService.upload(file);
      return R.ok().data("file",fileUrl);
    }
}
java 复制代码
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.service.OssService;
import com.atguigu.yygh.oss.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Service
public class OssServiceImpl implements OssService {

    /**
     * @Description: 上传文件
     * @return:  文件的url
     * @param:文件流
     * @author: Mr zhan
     */
    @Override
    public String upload(MultipartFile file) {
        //1.获取文件的名称
        String filename = file.getOriginalFilename();
        //2.准备参数
                            //地域结点
        String endpoint=ConstantPropertiesUtil.END_POINT;
                            //唯一id
        String accessKeyId=ConstantPropertiesUtil.ACCESS_KEY_ID;
                            //id的对应的唯一secret
        String accessKeySecret=ConstantPropertiesUtil.ACCESS_KEY_SECRET;
                            //存储桶
        String bucketName=ConstantPropertiesUtil.BUCKET_NAME;
                            //文件存储的路径
        //   String objectName="用下面的filename代替";
        //3.创建客户端
        OSS ossClient= new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        filename=uuid+filename;
        //4.由于真实的开发需要,方便运营,因此需要分类格式如下:  2022/03/05/图片名称
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String month = format.format(new Date());
        filename=month+"/"+filename;
        //上传
        try {
            ossClient.putObject(bucketName,filename,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            ossClient.shutdown();
        }


        return "https://"+bucketName+"."+endpoint+"/"+filename;
    }
}
相关推荐
秃头摸鱼侠11 分钟前
MySQL查询语句(续)
数据库·mysql
MuYiLuck19 分钟前
【redis实战篇】第八天
数据库·redis·缓存
睡觉待开机20 分钟前
6. MySQL基本查询
数据库·mysql
大熊猫侯佩1 小时前
由一个 SwiftData “诡异”运行时崩溃而引发的钩深索隐(三)
数据库·swiftui·swift
大熊猫侯佩1 小时前
由一个 SwiftData “诡异”运行时崩溃而引发的钩深索隐(二)
数据库·swiftui·swift
大熊猫侯佩1 小时前
用异步序列优雅的监听 SwiftData 2.0 中历史追踪记录(History Trace)的变化
数据库·swiftui·swift
家庭云计算专家1 小时前
ONLYOFFICE协作空间3.1.1 企业版 介绍及部署说明:家庭云计算专家
运维·服务器·云计算·onlyoffice·协作空间
大熊猫侯佩1 小时前
由一个 SwiftData “诡异”运行时崩溃而引发的钩深索隐(一)
数据库·swiftui·swift
Ares-Wang1 小时前
负载均衡LB》》HAproxy
运维·数据库·负载均衡
AI.NET 极客圈1 小时前
.NET 原生驾驭 AI 新基建实战系列(四):Qdrant ── 实时高效的向量搜索利器
数据库·人工智能·.net