谷粒商城-day06-OSS的引入

使用逆向的前后端代码

这里的图片地址用的是 oss url

image-20210222095101242

新建一个菜单

这里使用逆向生成的模块文件,展示基本的列表和 crud

image-20210222095436357

复制到我们的 modules/product 目录下面

重启项目

image-20210222095612256

这是展示的效果,可以看到没有删除和新增按钮,这里需要权限判断才会 显示

image-20210222095730020

image-20210222100435790

这里让它默认返回 true

image-20210222100548067

可以看到我们的新增和批量删除都有了

image-20210222100726147 image-20210222100737625

测试一下

这里的细节还需要自己完善

效果优化和快速显示开关

关掉 eslint

image-20210222101111689

更改显示状态的页面控件

自定义列模板

image-20210222102213044

参考 elementui上面的资料,可以看出是基于插槽机制去实现的

<el-table-column
  prop="showStatus"
  header-align="center"
  align="center"
  label="显示状态"
>
  <template slot-scope="scope">
    <el-switch
      v-model="scope.row.showStatus"
      active-color="#13ce66"
      inactive-color="#ff4949"
    >
    </el-switch>
  </template>
</el-table-column>
<el-form-item label="显示状态" prop="showStatus">
  <el-switch
        v-model="dataForm.showStatus"
        active-color="#13ce66"
        inactive-color="#ff4949"
      />
</el-form-item>

对话框

增加对话框输入左侧的距离

 <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="140px">

label-width="140px"

image-20210222104106233
<el-switch
  v-model="scope.row.showStatus"
  active-color="#13ce66"
  inactive-color="#ff4949"
  @change="updateBrandStatus"
>
</el-switch>
updateBrandStatus(status) {
  console.log('最新状态:'  + status);
}

image-20210222104411899

测试接口

image-20210222110101875

这里还需要自定义配置 switch 激活的值

:active-value="1"

:inactive-value="0"

<el-table-column
  prop="showStatus"
  header-align="center"
  align="center"
  label="显示状态"
>
  <template slot-scope="scope">
    <el-switch
      v-model="scope.row.showStatus"
      active-color="#13ce66"
      inactive-color="#ff4949"
      @change="updateBrandStatus(scope.row)"
      :active-value="1"
      :inactive-value="0"
    >
    </el-switch>
  </template>
</el-table-column>
updateBrandStatus(data) {
      console.log("最新信息:" + data.showStatus);
      let { brandId, showStatus } = data;

      // 发送修改
      this.$http({
        url: this.$http.adornUrl("/product/brand/update"),
        method: "post",
        data: this.$http.adornData({ brandId, showStatus }, false)
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "状态更新成功"
        });
      });
    }

OSS

image-20210222112200540

新建一个bucket

image-20210222112408791 image-20210222112604775

参考这个

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

image-20210222112904379

地域节点

image-20210222113102671 image-20210222113214157

image-20210222113302272

image-20210222113411325

分配 oss 访问权限

@Test
    public void testUpload() throws FileNotFoundException {
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
        String accessKeyId = "xxxxxxxxxxxxxx";
        String accessKeySecret = "xxxxxxxxxxxxxxxx";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传文件到指定的存储空间(bucketName)并将其保存为指定的文件名称(objectName)。
        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\15292\\Desktop\\zz.jpg");

        ossClient.putObject("gulimall-hello-zz", "zz.jpg", fileInputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        System.out.println("上传成功");
    }

image-20210222114623465

image-20210222114519738

demo 测试

使用 starter 的方式

在 common 里面引入

<!--ali oss-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>
spring:
    alicloud:
      access-key: LTAIxxxxxxxxx
      secret-key: HFTxxxxxxxxxxxxxxx
      oss:
        endpoint: oss-cn-beijing.aliyuncs.com

直接 注入 OssClient

服务端签名

image-20210222135154404
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhouzhou.gulimall</groupId>
    <artifactId>gulimall-third-party</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>gulimall-third-party</name>
    <description>第三方服务</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2020.0.1</spring-cloud.version>
    </properties>
    <dependencies>
        <!--ali oss-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
        </dependency>
        <dependency>
            <groupId>com.zhouzhou.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>


    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

image-20210222135833621 image-20210222140126018
spring.application.name=gulimall-third-party
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=91736e2d-24ef-4a02-8d05-715377a82824

spring.cloud.nacos.config.ext-config[0].data-id=oss.yml
spring.cloud.nacos.config.ext-config[0].group=DEFAULT_GROUP
spring.cloud.nacos.config.ext-config[0].refresh=true

以上是配置中心

<dependency>
            <groupId>com.zhouzhou.gulimall</groupId>
            <artifactId>gulimall-common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <exclusions>
<!--                排除掉数据库相关的配置-->
                <exclusion>
                    <groupId>com.baomidou</groupId>
                    <artifactId>mybatis-plus-boot-starter</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

  application:
    name: gulimall-third-party

server:
  port: 30000

注册中心

然后加上注解

package com.zhouzhou.gulimall.thirdparty;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;


@EnableDiscoveryClient
@SpringBootApplication
public class GulimallThirdPartyApplication {

    public static void main(String[] args) {
        SpringApplication.run(GulimallThirdPartyApplication.class, args);
    }

}

启动

这里遇到了三个坑。第一个是 pom 里面指定 springcloud 版本的时候的问题

第二个是,这里的配置需要新建在对应的名称空间下面

第三个是,yml文件的格式

image-20210222141952362

在我们抽离出来的第三方服务模块中再次测试

image-20210222142242063
package com.zhouzhou.gulimall.thirdparty.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.zhouzhou.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
public class OssController {

    @Autowired
    OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;



    @RequestMapping("/oss/policy")
    public R policy() {
        // https://gulimall-hello-zz.oss-cn-beijing.aliyuncs.com/zz.jpg
        String bucket = "gulimall-hello-zz";
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。


        Map<String, String> respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }

        return R.ok().put("data",respMap);
    }

}
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    alicloud:
      access-key: xxx
      secret-key: xxx
      oss:
        endpoint: oss-cn-beijing.aliyuncs.com
        bucket: gulimall-hello-zz


  application:
    name: gulimall-third-party

server:
  port: 30000
image-20210222151055553
- id: third_party_route
  uri: lb://gulimall-third-party
  predicates:
    - Path=/api/thirdparty/**
  filters:
    - RewritePath=/api/thirdparty/(?<segment>.*),/$\{segment}

网关的配置 http://localhost:88/api/thirdparty/oss/policy

image-20210222152801064

前后端联调

把 upload 文件夹放到 components 文件夹下面

image-20210222153253821

单文件和多文件都需要修改这个属性

import singleUpload from "@/components/upload/singleUpload"

export default {
  components: { singleUpload },

先引入组件

<el-form-item label="品牌logo地址" prop="logo">
  <single-upload v-model="dataForm.logo"></single-upload>
</el-form-item>
image-20210222154405040

配置跨域

image-20210222154528719

测试

image-20210222154638525

去掉斜杠

image-20210222154720761

image-20210222154922138

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值