相關網址:七牛開發者中心
相關網站: 七牛開發者中心
上傳流程概述
- 后端生成上傳憑證:服務器端使用七牛云 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>