服务器更替
This commit is contained in:
+30
-41
@@ -1,65 +1,54 @@
|
||||
import Crypto from 'crypto-js'
|
||||
import {Base64} from 'js-base64'
|
||||
import {i18n} from "@/locale";
|
||||
import {useUserStore} from '@/store'
|
||||
|
||||
const env = {
|
||||
uploadImageUrl: 'https://wendy123.oss-ap-southeast-1.aliyuncs.com/', // 默认存在根目录,可根据需求改
|
||||
accessKeySecret: 'TSZOD1jULKPFsNp2zKhAopLe3c3AiH', // accessKeySecret 去你的阿里云上控制台上找
|
||||
ossAccessKeyId: 'LTAI5tQq1bSBFCfsbvwX6DqQ', // AccessKeyId 去你的阿里云上控制台上找
|
||||
timeout: 87600, // 这个是上传文件时Policy的失效时间
|
||||
const baseUrl = import.meta.env.VITE_SERVER_BASEURL
|
||||
|
||||
function getClientId() {
|
||||
return 'e5cd7e4891bf95d1d19206ce24a7b32e'
|
||||
}
|
||||
|
||||
const getPolicyBase64 = function (): string {
|
||||
const date = new Date()
|
||||
date.setHours(date.getHours() + env.timeout)
|
||||
const expirationTime = date.toISOString()
|
||||
const policyText = {
|
||||
expiration: expirationTime, // 设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了
|
||||
conditions: [
|
||||
['content-length-range', 0, 2000 * 1024 * 1024], // 设置上传文件的大小限制,2G
|
||||
],
|
||||
function parseUploadResult(rawData: any): string {
|
||||
const data = typeof rawData === 'string' ? JSON.parse(rawData) : rawData
|
||||
if (!data || data.code !== 200) {
|
||||
throw new Error(data?.msg || '上传失败')
|
||||
}
|
||||
|
||||
return Base64.encode(JSON.stringify(policyText))
|
||||
return (
|
||||
data?.data?.url ||
|
||||
data?.data?.fullUrl ||
|
||||
data?.data?.fileUrl ||
|
||||
data?.data?.link ||
|
||||
data?.data
|
||||
)
|
||||
}
|
||||
|
||||
const getSignature = function (policyBase64: string): string {
|
||||
const bytes = Crypto.HmacSHA1(policyBase64, env.accessKeySecret)
|
||||
return Crypto.enc.Base64.stringify(bytes)
|
||||
}
|
||||
|
||||
// 上传图片到阿里云oss
|
||||
// 上传图片(走后端接口 /resource/oss/upload)
|
||||
const upload = function (filePath: string, suffix = '.png', dir = 'app/image/') {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!filePath) {
|
||||
return uni.showToast({icon: "none", title: i18n.global.t('common.prompt.picture-wrong-please-try-again')})
|
||||
}
|
||||
|
||||
// 图片名字 可以自行定义,这里是采用当前的时间戳 + 150内的随机数来给图片命名的
|
||||
const fileKey = dir + new Date().getTime() + Math.floor(Math.random() * 150) + suffix
|
||||
|
||||
const aliyunServerURL = env.uploadImageUrl // OSS地址,需要https
|
||||
const policyBase64 = getPolicyBase64()
|
||||
const signature = getSignature(policyBase64) // 获取签名
|
||||
const userStore = useUserStore()
|
||||
const token = userStore.token
|
||||
const clientId = getClientId()
|
||||
|
||||
uni.uploadFile({
|
||||
url: aliyunServerURL, // 开发者服务器 url
|
||||
url: baseUrl + '/resource/oss/upload',
|
||||
filePath: filePath, // 要上传文件资源的路径
|
||||
name: 'file', // 必须填file
|
||||
formData: {
|
||||
key: fileKey,
|
||||
policy: policyBase64,
|
||||
OSSAccessKeyId: env.ossAccessKeyId,
|
||||
signature: signature,
|
||||
success_action_status: '200',
|
||||
header: {
|
||||
Authorization: token ? `Bearer ${token}` : '',
|
||||
clientid: clientId,
|
||||
},
|
||||
success: function (res) {
|
||||
console.log(res)
|
||||
if (res.statusCode !== 200) {
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
reject(new Error('upload error:' + JSON.stringify(res)))
|
||||
return
|
||||
}
|
||||
resolve(aliyunServerURL + fileKey)
|
||||
try {
|
||||
resolve(parseUploadResult(res.data))
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
},
|
||||
fail: function (err) {
|
||||
console.log(err)
|
||||
|
||||
+46
-50
@@ -1,35 +1,5 @@
|
||||
import CryptoJS from 'crypto-js'
|
||||
import {Base64} from 'js-base64'
|
||||
import {i18n} from '@/locale'
|
||||
|
||||
// === 👉 请在这里填写你的 AWS 信息 ===
|
||||
const S3Config = {
|
||||
bucket: 'cheflink', // 你的存储桶名称
|
||||
region: 'us-east-1', // 桶所在区域
|
||||
accessKeyId: 'AKIA3LKQVMAPD3KFPJGS',
|
||||
secretKey: 'tV7yvBESDPemtiHGlFOg/oFxz3L1BNXu8KutKjZS',
|
||||
timeout: 0.1 // 签名有效时间(小时)
|
||||
}
|
||||
|
||||
// === 签名函数 ===
|
||||
function getPolicyBase64(): string {
|
||||
const expiration = new Date(Date.now() + 10 * 60 * 1000).toISOString() // 10分钟有效
|
||||
const policyText = {
|
||||
expiration,
|
||||
conditions: [
|
||||
{bucket: S3Config.bucket},
|
||||
['starts-with', '$key', 'cheflink/'],
|
||||
['starts-with', '$Content-Type', 'image/']
|
||||
]
|
||||
}
|
||||
return Base64.encode(JSON.stringify(policyText))
|
||||
}
|
||||
|
||||
|
||||
function getSignature(policyBase64: string): string {
|
||||
const bytes = CryptoJS.HmacSHA1(policyBase64, S3Config.secretKey)
|
||||
return CryptoJS.enc.Base64.stringify(bytes)
|
||||
}
|
||||
import {useUserStore} from '@/store'
|
||||
|
||||
// === 图片压缩函数 ===
|
||||
function compressImageIfNeeded(filePath: string, size: number): Promise<string> {
|
||||
@@ -89,8 +59,34 @@ function compressImageIfNeeded(filePath: string, size: number): Promise<string>
|
||||
})
|
||||
}
|
||||
|
||||
// === S3 上传函数 ===
|
||||
const uploadToS3 = async function (filePath: string, suffix = '.jpg', dir = 'cheflink/'): Promise<string> {
|
||||
function getClientId() {
|
||||
return 'e5cd7e4891bf95d1d19206ce24a7b32e'
|
||||
}
|
||||
|
||||
function parseUploadResult(rawData: any): string {
|
||||
const data = typeof rawData === 'string' ? JSON.parse(rawData) : rawData
|
||||
// 兼容不同后端返回格式:有的返回 { code: 200, data: ... },有的直接返回 { url: ... }
|
||||
if (data?.code !== undefined && String(data.code) !== '200') {
|
||||
throw new Error(data?.msg || '上传失败')
|
||||
}
|
||||
const result = (
|
||||
data?.data?.url ||
|
||||
data?.data?.fullUrl ||
|
||||
data?.data?.fileUrl ||
|
||||
data?.data?.link ||
|
||||
data?.url ||
|
||||
data?.fileUrl ||
|
||||
data?.link ||
|
||||
data?.data
|
||||
)
|
||||
if (!result || typeof result !== 'string') {
|
||||
throw new Error(data?.msg || '上传成功但未返回文件地址')
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// 走后端上传接口:/resource/oss/upload
|
||||
const uploadToS3 = async function (filePath: string): Promise<string> {
|
||||
if (!filePath) {
|
||||
uni.showToast({icon: 'none', title: i18n.global.t('common.prompt.picture-wrong-please-try-again')})
|
||||
return Promise.reject(new Error('filePath is empty'))
|
||||
@@ -120,32 +116,32 @@ const uploadToS3 = async function (filePath: string, suffix = '.jpg', dir = 'che
|
||||
return Promise.reject(err)
|
||||
}
|
||||
|
||||
// 文件名
|
||||
const filename = Date.now() + Math.floor(Math.random() * 1000) + suffix
|
||||
const key = dir + filename
|
||||
const policyBase64 = getPolicyBase64()
|
||||
const signature = getSignature(policyBase64)
|
||||
const uploadUrl = `https://${S3Config.bucket}.s3.${S3Config.region}.amazonaws.com/`
|
||||
const userStore = useUserStore()
|
||||
const token = userStore.token
|
||||
const clientId = getClientId()
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.uploadFile({
|
||||
url: uploadUrl,
|
||||
url: '/resource/oss/upload',
|
||||
filePath: uploadPath,
|
||||
name: 'file',
|
||||
formData: {
|
||||
key,
|
||||
AWSAccessKeyId: S3Config.accessKeyId,
|
||||
policy: policyBase64,
|
||||
signature,
|
||||
'Content-Type': 'image/jpeg',
|
||||
header: {
|
||||
Authorization: token ? `Bearer ${token}` : '',
|
||||
clientid: clientId,
|
||||
},
|
||||
success: res => {
|
||||
if (res.statusCode === 204) {
|
||||
uni.showToast({icon: 'none', title: i18n.global.t('common.operation-success')})
|
||||
resolve(`${uploadUrl}${key}`)
|
||||
} else {
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
uni.showToast({icon: 'none', title: i18n.global.t('common.prompt.up-failed')})
|
||||
reject(new Error(`上传失败,状态码: ${res.statusCode}`))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const fileUrl = parseUploadResult(res.data)
|
||||
uni.showToast({icon: 'none', title: i18n.global.t('common.operation-success')})
|
||||
resolve(fileUrl)
|
||||
} catch (error) {
|
||||
uni.showToast({icon: 'none', title: i18n.global.t('common.prompt.up-failed')})
|
||||
reject(error)
|
||||
}
|
||||
},
|
||||
fail: err => {
|
||||
|
||||
Reference in New Issue
Block a user