Vue+SpringBoot整合七牛云图片上传

SpringBoot整合七牛云图片上传

1、注册七牛云

七牛云官网:七牛云官网
注册登陆以后点击管理控制台
在这里插入图片描述
在对象存储中添加新的存储空间。
Vue+SpringBoot整合七牛云图片上传_第1张图片
点击控制台右上角头像选择密钥管理
Vue+SpringBoot整合七牛云图片上传_第2张图片
在密钥管理界面有AK和SK,这在后面的代码要用到。
接下来就是代码的编写了。

2、疑问

网上其他教程都在application.yml配置了相关的ak,sk,bucket以及baseuploadurl。我在七牛官方文档看好像并没有用到baseUploadUrl,七牛上传图片需要在本地缓存一个临时对象吗?希望有大佬看到我的问题可以帮忙解答。

3、编写相关实现代码

引入七牛云的相关依赖:

		<!--七牛云-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.28</version>
        </dependency>
        <!--Gson包-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

Service层:

import com.qiniu.http.Response;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


public interface UploadPictureService {
     
    String uploadPicture(MultipartFile file) throws IOException;
}

ServiceImpl层

import com.google.gson.Gson;
import com.learn.wyg.service.UploadPictureService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.Json;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Random;


/**
 * @description:
 * @author: WYG
 * @time: 2020/4/18 15:46
 */
@Service
public class UploadPictureServiceimpl implements UploadPictureService {
     


    @Override
    public String uploadPicture(MultipartFile file) throws IOException {
     
        String qiniuUrl = "你的外链域名";
        Configuration configuration = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(configuration);
        String accessKey = "你的AK";
        String secretKey = "你的SK";
        String bucket = "你的存储空间名称";
        String key = getRandomCharacterAndNumber(10) + ".png";//生成随机文件名
        Auth auth = Auth.create(accessKey,secretKey);
        String uptoken = auth.uploadToken(bucket);
        String responseUrl = "";
        try{
     
            byte[] localFile = file.getBytes();
            Response response = uploadManager.put(localFile,key,uptoken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            responseUrl = responseUrl + qiniuUrl + putRet.key;
        }catch (QiniuException e){
     
            Response r = e.response;
        }
        return responseUrl;
    }

    public 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;
    }
}

Controller层

import com.learn.wyg.service.UploadPictureService;
import com.learn.wyg.utils.JsonResult;
import com.qiniu.http.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @description:
 * @author: WYG
 * @time: 2020/4/18 15:54
 */

@RestController
@RequestMapping("/api/upload")
public class UploadController {
     
    @Autowired
    private UploadPictureService uploadPictureService;

    @PostMapping("/picture")
    @CrossOrigin
    public JsonResult<String> uploadPicture(@RequestParam("file") MultipartFile multipartFile) throws IOException {
     
        String pictureUrl = uploadPictureService.uploadPicture(multipartFile);
        return new JsonResult<String>(pictureUrl,"200","success");
    }
}

Controller层
以上代码可以直接拿去用。

4、前端使用Element-ui的upload组件实现上传

			<el-upload
                class="upload-picture"
                action="http://localhost:8081/api/upload/picture"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-success="handleSuccess"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
	handleRemove (file, fileList) {
     
      console.log(file, fileList)
    },
    handlePreview (file) {
     
      console.log(file)
    },
    handleExceed (files, fileList) {
     
      this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${
       files.length} 个文件,共选择了 ${
       files.length + fileList.length} 个文件`)
    },
    beforeRemove (file, fileList) {
     
      return this.$confirm(`确定移除 ${
       file.name}?`)
    },
    handleSuccess (response, file, fileList) {
     
      this.ForumAndTag.forum.first_picture = response.data
      this.$message.success(this.ForumAndTag.forum.first_picture)
    }

可直接在on-success对应的函数中获取上传图片后后端返回的信息,例如图片地址,然后通过图片地址进行展示
具体可访问elementui官网:Element-ui
upload组件部分参数
Vue+SpringBoot整合七牛云图片上传_第3张图片

当然,对象存储还有阿里云的对象存储,不过我还没有用过,以后用了再介绍。

你可能感兴趣的:(Vue,Spring,upload,云存储,java,spring,vue.js)