课堂笔记20230818

亮子 2023-08-19 02:33:44 10405 0 0 0

OSS

  • 相关资料

第一节 开通OSS服务以及增加授权
第二节 文件上传到阿里云OSS介绍
第三节 阿里云OSS的jdk安装
第四节 阿里云OSS上传工具类

  • 附件配置文件修改
package com.bw2102a.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
@Data
public class OssConfig {

    // 区域
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    // 桶名称
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    // key
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    // 密钥
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    // 主域名
    @Value("${aliyun.oss.hostName}")
    private String hostName;


    @Bean
    public OSS ossClientBuilder(){
        OSS ossClientBuilder = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        return ossClientBuilder;
    }

}
  • nacos上yaml文件配置

图片alt

aliyun:
  oss:
    endpoint: http://oss-cn-beijing.aliyuncs.com
    accessKeyId: LTAI4FtqoX9aXnwt5WRPVtJ9
    accessKeySecret: BjxfqbWKvpusWM328UGzwYT8PQYlm5
    hostName: https://images.shenmazong.com/
    bucketName: shenmazong
  • controller的代码
package com.bw2102a.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.bw2102a.config.OssConfig;
import com.bw2102a.domain.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 军哥
 * @version 1.0
 * @description: OssController
 * @date 2023/8/18 16:15
 */

@RestController
@Slf4j
@RequestMapping(value = "/oss")
public class OssController {

    @Autowired
    OSS ossClientBuilder;

    @PostMapping(value = "/uploadImage")
    public ResultVo uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 转换文件名字
        String fileName = file.getOriginalFilename();
        UUID uuid = UUID.randomUUID();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String newName = "temp/"+uuid.toString() + suffix;

        // 上传文件
        PutObjectResult result = ossClientBuilder.putObject("shenmazong", newName, file.getInputStream());
//        String url = ossConfig.getHostName() + newName;
        String url = "https://images.shenmazong.com/"  + newName;

        return ResultVo.SUCCESS(url);
    }

}

vue单个图片上传

  • html代码

图片alt

  • 数据区代码

图片alt

  • 方法区代码

图片alt

vue多文件上传

  • js

图片alt

  • data

图片alt

  • method

图片alt

vue效果

图片alt

vue上传文件的完整代码

<template>
  <div
    style="
      width: 600px;
      height: auto;
      margin-left: 500px;
      border-radius: 15%;
      border-color: black;
    "
  >
    <div style="width: 600px; height: 40px; margin: auto; text-align: center">
      <h3>新增页面</h3>
    </div>
    <div>
      <el-form :model="userForm">
        <el-form-item label="用户名">
          <el-input v-model="userForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userForm.userMobile" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userForm.userPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9090/user/oss/uploadImage"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="token"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="项目经历">
          <el-upload
            class="upload-demo"
            action="http://localhost:9090/user/oss/uploadImage"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleFileSuccess"
            multiple
            :limit="3"
            :headers="token"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件,且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="性别">
          <template>
            <el-radio-group v-model="userForm.userSex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">未知</el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <el-form-item label="权限">
          <div class="block">
            <span class="demonstration"></span>
            <el-cascader
              v-model="value"
              :options="options"
              @change="handleChange"
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="角色">
          <template>
            <el-checkbox-group v-model="checkList">
              <el-checkbox label="复选框 A"></el-checkbox>
              <el-checkbox label="复选框 B"></el-checkbox>
              <el-checkbox label="复选框 C"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="insertUser()">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { insertUserApi } from "@/api/insertApi";
import { getProductTypeTree } from "@/api/userApi";

export default {
  data() {
    return {
      userForm: {
        userAvatar: "",
        userMobile: "",
        userName: "",
        userPass: "",
        userSex: "",
      },
      checkList: ["选中且禁用", "复选框 A"],
      value: [],
      options: [],
      imageUrl: null,
      token: null,
      fileList: [],
      fileListVar: [],
    };
  },
  mounted() {
    this.token = { token: window.sessionStorage.getItem("token") };
    getProductTypeTree().then((res) => {
      if (res.data.code == 200) {
        this.options = res.data.data;
      }
    });
  },
  methods: {
    handleChange(value) {
      console.log(value);
    },
    insertUser() {
      insertUserApi(this.userForm).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("用户增加成功");
          this.$router.push("/index");
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      console.log("handleAvatarSuccess", res);
      this.imageUrl = res.data;
      console.log("url", this.imageUrl);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }

      return isJPG;
    },
    handleRemove(file, fileList) {
      console.log('handleRemove', file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    handleFileSuccess(res, file) {
        console.log('handleFileSuccess1', res);
        console.log('handleFileSuccess2', this.fileList);
        this.fileListVar.push(res.data)
        console.log('handleFileSuccess3', this.fileListVar);

    }
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>