当前位置: 首页 > news >正文

七牛云图片上传 前后端全过程

相关网址:七牛开发者中心

相关网站: 七牛开发者中心

上传流程概述

  1. 后端生成上传凭证:服务器端使用七牛云 SDK 生成上传凭证(uptoken)
  2. 前端获取凭证:前端通过 API 向后端请求上传凭证
  3. 前端上传图片:前端使用获取的凭证将图片上传到七牛云
  4. 处理上传结果:七牛云返回上传结果,前端或后端处理结果

后端 Java 代码实现

首先需要添加七牛云 SDK 依赖:

<dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><version>[7.7.0, 7.7.99]</version>
</dependency>

还需要在 application.properties 中配置七牛云密钥:

# 七牛云配置
qiniu.accessKey=你的AccessKey
qiniu.secretKey=你的SecretKey
qiniu.bucket=你的存储空间名称
qiniu.domain=你的存储空间域名

QiniuController.java:

package com.example.controller;import com.qiniu.util.Auth;
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.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/api/qiniu")
public class QiniuController {@Value("${qiniu.accessKey}")private String accessKey;@Value("${qiniu.secretKey}")private String secretKey;@Value("${qiniu.bucket}")private String bucket;@Value("${qiniu.domain}")private String domain;/*** 获取七牛云上传凭证*/@GetMapping("/token")public Map<String, Object> getUploadToken() {Map<String, Object> result = new HashMap<>();try {// 创建Auth对象,用于生成凭证Auth auth = Auth.create(accessKey, secretKey);// 生成上传凭证,有效期3600秒String upToken = auth.uploadToken(bucket, null, 3600, null);result.put("code", 200);result.put("message", "获取凭证成功");result.put("data", new HashMap<String, Object>() {{put("token", upToken);put("domain", domain);}});} catch (Exception e) {result.put("code", 500);result.put("message", "获取凭证失败: " + e.getMessage());}return result;}
}

前端 Vue3 代码实现

<template><view class="container"><button @click="chooseImage">选择图片</button><view class="image-list"><image v-for="(img, index) in imageList" :key="index" :src="img.url" mode="aspectFill"/></view><view class="progress" v-if="uploading"><text>上传中: {{ progress }}%</text></view></view>
</template><script setup>
import { ref, reactive } from 'vue';
import { uploadFile } from '@dcloudio/uni-app';// 状态管理
const imageList = ref([]);
const uploading = ref(false);
const progress = ref(0);// 选择图片
const chooseImage = async () => {try {const res = await uni.chooseImage({count: 9,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera']});// 遍历选择的图片并上传for (const tempFile of res.tempFilePaths) {await uploadImage(tempFile);}} catch (e) {uni.showToast({title: '选择图片失败',icon: 'none'});}
};// 获取七牛云上传凭证
const getQiniuToken = async () => {const res = await uni.request({url: 'http://你的后端地址/api/qiniu/token',method: 'GET'});if (res.data.code === 200) {return res.data.data;} else {throw new Error('获取上传凭证失败');}
};// 上传图片到七牛云
const uploadImage = async (filePath) => {try {uploading.value = true;progress.value = 0;// 获取七牛云上传凭证const { token, domain } = await getQiniuToken();// 生成唯一文件名const fileName = `image_${new Date().getTime()}_${Math.floor(Math.random() * 10000)}.jpg`;// 上传到七牛云const uploadTask = uni.uploadFile({url: 'https://up.qiniup.com',filePath: filePath,name: 'file',formData: {key: fileName,token: token}});// 监听上传进度uploadTask.onProgressUpdate((res) => {progress.value = res.progress;});// 等待上传完成const uploadRes = await uploadTask;if (uploadRes.statusCode === 200) {const data = JSON.parse(uploadRes.data);// 将上传成功的图片添加到列表imageList.value.push({url: `${domain}/${data.key}`,key: data.key});uni.showToast({title: '上传成功',icon: 'success'});} else {uni.showToast({title: '上传失败',icon: 'none'});}} catch (e) {uni.showToast({title: '上传出错: ' + e.message,icon: 'none'});} finally {uploading.value = false;}
};
</script><style scoped>
.container {padding: 20rpx;
}button {margin-bottom: 20rpx;
}.image-list {display: flex;flex-wrap: wrap;gap: 10rpx;
}.image-list image {width: 200rpx;height: 200rpx;border-radius: 10rpx;
}.progress {margin-top: 20rpx;text-align: center;color: #007AFF;
}
</style>

相关文章:

  • vue封装的echarts组件被同一个页面多次引用只显示一个的问题
  • Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘xxx’)
  • Win10重装系统 (重生篇:我在华强修电脑)
  • AIGC方案-java实现视频伪动效果
  • SpringBoot + 自建GitLab + Jenkins + CentOS Stream 9 来实现自动化部署
  • 御微半导体面试总结
  • 内存泄漏系列专题分析之二十:camx swap内存泄漏实例分析
  • Jenkins + Docker + Kubernetes(JKD)自动化部署全链路实践
  • 基于OpenCV的图像增强技术:直方图均衡化与自适应直方图均衡化
  • 零基础设计模式——行为型模式 - 备忘录模式
  • LVS 负载均衡详解:四层转发原理与三种经典模式全面解析
  • eureka如何绕过 LVS 的虚拟 IP(VIP),直接注册服务实例的本机真实 IP
  • 我们来学mysql -- 8.4版本记录慢查询
  • Spring MVC扩展与SSM框架整合
  • 传统机器学习与大模型 + Prompt 的对比示例
  • 计算机系统概述(5)
  • 使用Docker申请Let‘s Encrypt证书
  • 谈文件系统
  • AI Agent核心技术深度解析:Function Calling与ReAct对比报告
  • vue3笔记(1)自用
  • 网站访客代码js/网络推广专员岗位职责
  • 做网站好不好/信息流优化
  • 大量图片展示网站模板/微指数官网
  • 网站中的表单怎么做/收录入口在线提交
  • 铁岭做网站公司哪家好/山东关键词快速排名
  • 六安做网站的/湖州seo排名