相关网址:七牛开发者中心
相关网站: 七牛开发者中心
上传流程概述
- 后端生成上传凭证:服务器端使用七牛云 SDK 生成上传凭证(uptoken)
- 前端获取凭证:前端通过 API 向后端请求上传凭证
- 前端上传图片:前端使用获取的凭证将图片上传到七牛云
- 处理上传结果:七牛云返回上传结果,前端或后端处理结果
后端 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>