springBoot+vue简单阿里OSS上传

后端

nameincloud
END_POINTxxxxxxxxxxxxxxxxxxxxxxxxx
ACCESS_KEY_IDxxxxxxxxxxxxxxxxxxxxxxxxx
ACCESS_KEY_SECRETxxxxxxxxxxxxxxxxxxxxxxxxx
BUCKETxxxxxxxxxxxxxxxxxxxxxxxxx

导入依赖

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.5</version>
</dependency>

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

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.1</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
</dependency>

配置+工具

OssConstant

/**
 * 配置常量
 */
public class OssConstant {
    //外网访问oss服务器的域名
    public static final String END_POINT = "xxxxxxxxxxxxxxxxxxxxxxxxx";

    //访问KEY_ID
    public static final String ACCESS_KEY_ID = "xxxxxxxxxxxxxxxxxxxxxxxxx";

    //访问密钥
    public static final String ACCESS_KEY_SECRET = "xxxxxxxxxxxxxxxxxxxxxxxxx";

    //文件存储空间
    public static final String BUCKET = "xxxxxxxxxxxxxxxxxxxxxxxxx";
}

OssConfig

/**
 * OSS客户端配置类
 */
@Configuration
public class OssConfig {
    @Bean
    public OSSClient ossClient(){
        return new OSSClient(OssConstant.END_POINT,OssConstant.ACCESS_KEY_ID,OssConstant.ACCESS_KEY_SECRET);
    }
}

Result

/**
 * 接口返回对象
 */
@Data
public class Result<T> {
    public static final String DEFAULT_FAILED_CODE = "9998";
    public static final String DEFAULT_FAULT_CODE = "9999";
    public static final String DEFAULT_SUCCESS_CODE = "200";

    /**
     * 错误返回时的错误码
     */
    private String code;

    /**
     * 错误返回时的错误信息
     */
    private String message;

    /**
     * status为SC_OK时的JSON字符串
     */
    private T data;

    /**
     * 构造函数(成功返回时使用)
     *
     * @param object 支持转换JSON格式的Java对象
     */
    public Result(T object) {

        this.code = DEFAULT_SUCCESS_CODE;
        this.message = "";
        this.data = object;
    }

    /**
     * 构造函数(失败返回时使用)
     */
    public Result(String code, String message) {

        this.code = code;
        this.message = message;
        this.data = null;
    }

    public static <T> Result<T> ok() {
        return new Result<>(null);
    }

    public static <T> Result<T> ok(T data) {
        return new Result<>(data);
    }

    public static <T> Result<T> failed(String message) {

        return new Result<>(DEFAULT_FAILED_CODE, message);
    }

    public static <T> Result<T> failed(String code, String message) {

        return new Result<>(code, message);
    }

    public static <T> Result<T> fault(String message) {

        return new Result<>(DEFAULT_FAULT_CODE, message);
    }

    public static <T> Result<T> fault(String code, String message) {

        return new Result<>(code, message);
    }
}

控制层

OssController

/**
 * 带设置文件夹的OSS存储
 * @param file 上传的文件
 * @return
 */
@PostMapping("/toUp")
public Result<String> toUp(@RequestParam("file") MultipartFile file){
    InputStream inputStream = null;
    try {
        inputStream = file.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String url = ossService.uploadFileAvatar(inputStream,file.getOriginalFilename());
    if(StringUtils.isEmpty(url)){
        return Result.failed("上传失败");
    }
    return Result.ok(url);
}

业务逻辑层

OssServiceImpl

@Override
public String uploadFileAvatar(InputStream inputStream,String originalFilename) {
    // 获取OSS的配置信息
    // 外网连接地址
    String endpoint = OssConstant.END_POINT;
    // AccessKeyId
    String accessKeyId = OssConstant.ACCESS_KEY_ID;
    // AccessKeySecret
    String accessKeySecret = OssConstant.ACCESS_KEY_SECRET;
    // 存储空间
    String bucketName = OssConstant.BUCKET;

    // 创建OSS实例
    OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
    // 配置OSS文件夹名称
    String folder = new DateTime().toString("yyyy-MM-dd");
    // 防止名字重复,这里设置随机UUID
    String fileName = UUID.randomUUID().toString();
    // originalFilename是上传的文件名称,这里是将名称进行截取,只取后缀部分  比如.jpg
    String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

    // folder日期作为文件夹名称,--是一个文件夹,//这是分成多个文件夹。fileName是OSS存储的文件的名称,拼上后缀
    String objectName = folder + "/" + fileName + fileExtension;
    // 查看url时候本来是下载,这样的话就是查看,只能查看图片
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentType("image/jpg");
    // 完成上传
    ossClient.putObject(bucketName, objectName, inputStream);
    // 关闭实例
    ossClient.shutdown();

    // 这是我们可以访问的文件链接地址
    String url = "http://"+bucketName+"."+endpoint+"/"+objectName;
    System.out.println(url);
    // 返回文件地址,方便我们存入数据库
    return url;
}

前端

upload.vue

<template>
  <div>
    <el-upload
      action="http://localhost:8000/oss/toUp"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>

<style>
</style>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值