七牛云实现三方存储_SpringBoot+ElementUI+VUE

七牛云实现三方存储_SpringBoot+ElementUI+VUE

引言:

       本文主要分享了有关三方存储的知识,使用的三方是七牛云,运用了SpringBoot+VUE的技术,合理的使用文档进行编写;包括:七牛云的注册、使用、SpringBoot后台的实现以及VUE前台的实现(附源码);

1. 注册七牛云

七牛云网址:https://portal.qiniu.com/

2. 创建存储空间

跟着步骤即可

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

点击进去后选择文件管理

在这里插入图片描述

3. 运行

首先手动上传一个文件测试

  • 外域路径加文件名就可以访问了

在这里插入图片描述=========

在这里插入图片描述

4. Springboot整合ElementUI及七牛云存储图片

这里使用Springboot+ElementUI+vue来实现图片的存储;

  • 项目的创建,环境的搭建可以参考之前的文章;

4.1 添加依赖

首先是添加依赖

<dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.2</version>
            <scope>compile</scope>
        </dependency>
        <!--Gson包-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>happy-dns-java</artifactId>
            <version>0.1.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--七牛服务器-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.28</version>
        </dependency>

4.2 查看信息

点开右上角头像-----密钥管理

在这里插入图片描述

4.3 定义工具类

定义工具类,存放七牛云的基本信息

package com.sx.kak.utils;

/**
 * Created by Kak on 2020/9/15.
 */
public class VariableNames {
    
    
    //七牛AK
    public static final String accessKey = "XXXXXXXXXXXXXX";
    //七牛SK
    public static final String secretKey ="XXXXXXXXXXXXXX";
    //七牛的云存储空间名
    public static final String bucket ="kak-space";
    //对外访问的域名
    public static final String pubdomain ="http://XXXXXXXXXXXXXX.com/";
}

4.4 StudentFilePicture

接收的实体类

package com.sx.kak.po;

import lombok.Data;

/**
 * Created by Kak on 2020/9/15.
 */
@Data
public class StudentFilePicture {
    
    
    private int id;
    private String name;
    private String age;
    private String sex;
    private String imageUrl;
}

4.5 定义七牛云上传的工具类

核心代码来自七牛云文档

package com.sx.kak.utils;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.storage.Configuration;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Random;

/**
 * Created by Kak on 2020/9/15.
 */
public class QiniuUpload {
    
    
    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static final String ACCESS_KEY = VariableNames.accessKey; //这两个登录七牛
    private static final String SECRET_KEY = VariableNames.secretKey;
    //要上传的空间
    private static final String bucketName = VariableNames.bucket; //对应要上传到七牛上
    //密钥配置
    private static Auth auth =  Auth.create(ACCESS_KEY,SECRET_KEY);
    private static Configuration cfg  = new Configuration(Region.huanan());
    private static UploadManager uploadManager = new UploadManager(cfg);
    // 采用默认策略,只需设置存储空间名
    public static  String getUpToken(){
    
    
        return auth.uploadToken(bucketName);
    }
    /上传通用实现
    public static String uploadFile(MultipartFile file){
    
    
        try {
    
    
            byte[] uploadBytes = file.getBytes();//文件流转字节流
			//获取随机文件名
            String fileName = getRandomCharacterAndNumber(10)+".jpg";
            Response response = uploadManager.put(uploadBytes, fileName, getUpToken());
			//解析上传结果
            DefaultPutRet putPet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            //外部访问的资源地址
            String resUrl = VariableNames.pubdomain + putPet.key;
            return resUrl;
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

    private static String getRandomCharacterAndNumber(int length) {
    
    
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
    
    
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

            if ("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
    
    
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
                // int choice = 97; // 指定字符串为小写字母
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
            {
    
    
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
}

4.6 上传文件的Controller

uploadFile:回写图片

addP:后台控制台输出

package com.sx.kak.controller;

import com.sx.kak.po.StudentFilePicture;
import com.sx.kak.utils.QiniuUpload;
import com.sx.kak.vo.ActionResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by Kak on 2020/9/15.
 */
@RestController
@RequestMapping("/api")
@CrossOrigin
public class FileUploadController {
    
    
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ActionResult uploadFile(@RequestParam("file") MultipartFile file){
    
    
        ActionResult result = new ActionResult();
        result.setStatusCode(200);
//        上传文件
        String url = QiniuUpload.uploadFile(file);
        result.setData(url);
        return result;
    }
    @RequestMapping(value = "/addPicture",method = RequestMethod.POST)
    public ActionResult addP(@RequestBody StudentFilePicture studentFilePicture){
    
    
        ActionResult result = new ActionResult();
        result.setStatusCode(200);
        System.out.println(studentFilePicture);
        return result;
    }
}

4.7 Student.vue

配置路由略

利用ElementUI组件展示前端组件;

点击“添加学生信息(上传图片)”按钮时弹出模态窗体,当表单提交时反写图片;

<template>
  <div>
    <h2>七牛云上传图片</h2>
    <el-button type="primary" @click="addPicture()">添加学生信息(上传图片)</el-button>
    <!-- 弹出框 -->
    <el-dialog title="增加学生信息" :visible.sync="dialogFormVisible">
      <el-form :model="student">
        <el-upload
          action="http://localhost:8088/api/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="uploadOk"
        >
          <i class="el-icon-plus"></i>
          <el-dialog :visible.sync="dialogVisible" size="tiny">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-upload>
        <el-form-item label="学生ID" :label-width="formLabelWidth">
          <el-input v-model="student.id" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生姓名" :label-width="formLabelWidth">
          <el-input v-model="student.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" :label-width="formLabelWidth">
          <el-input v-model="student.sex" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生年龄" :label-width="formLabelWidth">
          <el-input v-model="student.age" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPictureStudent()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      dialogImageUrl: "",
      dialogVisible: false,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      student: {
     
     
        id: 0,
        name: "",
        sex: "",
        age: "",
        imageUrl: "",
      },
    };
  },
  methods: {
     
     
    uploadOk(response, file, fileList) {
     
     
      this.student.imageUrl = response.data;
    },
    addPicture: function () {
     
     
      this.dialogFormVisible = true;
    },
    handleRemove(file, fileList) {
     
     
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
     
     
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    addPictureStudent: function () {
     
     
      this.$axios
        .post('addPicture', {
     
     
          'id': this.student.id,
          'name': this.student.name,
          'sex': this.student.sex,
          'age': this.student.age,
          'imageUrl': this.student.imageUrl,
        })
        .then((response) => {
     
     
          if (response.data.statusCode == 200) {
     
     
            this.$message("add success");
            this.dialogFormVisible = false;
          }
        })
        .catch((error) => {
     
     
          this.$message(error);
        });
    },
  },
};
</script>
<style>
</style>
  • 对图片大小有限制

4.8 页面展示

vue首页

增加信息

后端输出

显示

猜你喜欢

转载自blog.csdn.net/weixin_42601136/article/details/108599984