【springboot+vue图片上传七牛云】

springboot+vue图片上传七牛云

vue端

  • 上传标签
 <el-upload
        multiple
        :action="uploadImg"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="uploadOk"
        :headers="headers"
      >
        <i class="el-icon-plus"></i>
        <el-dialog :visible.sync="dialogVisible" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-upload>
  • 数据
data() {
    return {
	  imageUrl: '',
      dialogImageUrl: "",
      dialogVisible: false,
      build: {
        imageUrl: ''
      },
      headers: {
        Authorization: "Bearer " + getToken()
      },
    };
  },
  • 方法
	handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    uploadOk(response, file, fileList) {
      this.build.imageUrl = response.data;
    },
    handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
     replyOk() {
     this.openReply = false
     if (this.build.imageUrl === '') {
       this.$modal.msgError("请上传图片");
     } else {
       const param = {
         'reply': this.textarea,
         'imageUrl': this.build.imageUrl,
         'buildId': this.selectRowId
       }
       addPicture(param).then(res => {
         if (res.code === 200) {
           this.$modal.msgSuccess("回复成功,工单完成")
           this.getList()
         }
       })
       .catch((error) => {
         this.$modal.error(error)
       })
     }
     
     this.textarea = '',
     this.build.imageUrl = '',
     this.selectRowId = null
   },

后端代码

  • 核心包
<!--        七牛核心包-->
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
            <version>7.2.28</version>
        </dependency>
        <!--        传输协议-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.2</version>
        </dependency>
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>happy-dns-java</artifactId>
            <version>0.1.6</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
  • 七牛云工具类
public class VariableNames {

    //七牛AK
    public static final String accessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    //七牛SK
    public static final String secretKey ="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    //七牛的云存储空间名
    public static final String bucket ="demo";
    //对外访问的域名
    public static final String pubdomain ="http://xxxxxxxxxxxxxxxxxxxx.com/";
}
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;
    }
}
  • controller层
	@PreAuthorize("@ss.hasPermi('system:build:upload')")
    @Log(title = "工单", businessType = BusinessType.UPDATE)
    @PostMapping("upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file){
        AjaxResult result = new AjaxResult();
        result.put("code",200);
//        上传文件
        String url = QiniuUpload.uploadFile(file);
        result.put("data",url);
        return result;
    }
  • 效果
    图片: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GafDhL2p-1676951643664)(在这里插入图片描述]
    )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~最好的自己~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值