Merge branch 'domain-dyn'
This commit is contained in:
@@ -52,6 +52,15 @@ export function getUserInfo() {
|
||||
method: 'GET'
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @description: getOssPolicyInfo
|
||||
*/
|
||||
export function getOssPolicyInfo() {
|
||||
return http.request({
|
||||
url: `${baseUrl}/v2/common/sts`,
|
||||
method: 'GET'
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @description: uploadCommon
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,18 @@
|
||||
import { http } from '@/utils/http/axios';
|
||||
|
||||
const baseUrl = '/api'
|
||||
|
||||
export function getDomainList(){
|
||||
return http.request({
|
||||
url: 'domain.txt',
|
||||
method: 'GET'
|
||||
},
|
||||
{
|
||||
withToken: false,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @description: sendSmsRegister
|
||||
*/
|
||||
|
||||
219
src/hooks/useUpload.ts
Normal file
219
src/hooks/useUpload.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import {getOssPolicyInfo} from "@/api";
|
||||
import {useUserStore} from "@/store/modules/user";
|
||||
import OSS from "ali-oss";
|
||||
|
||||
|
||||
type Options = {
|
||||
width: number,
|
||||
height: number,
|
||||
// type null(不传就是默认尺寸全等) | ratio (尺寸比例相等即可)
|
||||
type?: string,
|
||||
file: File,
|
||||
callBack?: Function
|
||||
}
|
||||
|
||||
|
||||
type Policy = {
|
||||
bucket: string,
|
||||
key: string,
|
||||
keyId: string,
|
||||
keySecret: string,
|
||||
region: string,
|
||||
token: string,
|
||||
|
||||
cdnDomain: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
* @returns
|
||||
*/
|
||||
export function useUpload() {
|
||||
|
||||
const userStore = useUserStore();
|
||||
|
||||
// header
|
||||
let header = {
|
||||
accessToken: userStore.getToken,
|
||||
};
|
||||
|
||||
let policy: Policy = {
|
||||
bucket: "",
|
||||
key: "",
|
||||
keyId: "",
|
||||
keySecret: "",
|
||||
region: "",
|
||||
token: "",
|
||||
cdnDomain: ""
|
||||
};
|
||||
|
||||
const init = () => {
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取oss配置
|
||||
*/
|
||||
const getOssPolicy = async () => {
|
||||
policy = await getOssPolicyInfo();
|
||||
return policy;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取header
|
||||
*/
|
||||
const getHeader = () => {
|
||||
header = {
|
||||
accessToken: userStore.getToken,
|
||||
};
|
||||
return header;
|
||||
};
|
||||
|
||||
/**
|
||||
* 自定义上传
|
||||
* @param customRequestOptions
|
||||
* @param callback
|
||||
*/
|
||||
// const customRequest = async (customRequestOptions, callback?: (arg0: string | undefined) => any) => {
|
||||
// await getOssPolicy();
|
||||
// const { file, withCredentials, onFinish, onError, onProgress } = customRequestOptions;
|
||||
// // 生成随机文件名
|
||||
// const getRandomFileName = () => {
|
||||
// const randomNum = Math.floor(Math.random() * 10000);
|
||||
// const timestamp = new Date().format('yyyyMMddhhmmss');
|
||||
// const extension = file.name.split(".").pop();
|
||||
// return `${timestamp}-${randomNum}.${extension}`;
|
||||
// }
|
||||
// const key: string = policy.dir + getRandomFileName();
|
||||
//
|
||||
// return new Promise((resolve, reject) => {
|
||||
// http.uploadFile({
|
||||
// url: policy.uploadHost,
|
||||
// method: RequestEnum.POST,
|
||||
// timeout: 1000 * 60 * 10,
|
||||
// withCredentials: withCredentials,
|
||||
// onUploadProgress: (obj) => {
|
||||
// onProgress && onProgress({ percent: Math.ceil((obj.progress || 0) * 100) });
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// data: {
|
||||
// OSSAccessKeyId: policy.accessKeyId,
|
||||
// signature: policy.signature,
|
||||
// policy: policy.policy,
|
||||
// key: key,
|
||||
// success_action_status: 200
|
||||
// },
|
||||
// file: file.file as File
|
||||
// })
|
||||
// .then(res => {
|
||||
// console.log("res", res);
|
||||
// onFinish && onFinish();
|
||||
// callback && callback(`${policy.host}/${key}`);
|
||||
// resolve(`${policy.host}/${key}`);
|
||||
// })
|
||||
// .catch((error) => {
|
||||
// callback && callback(undefined);
|
||||
// onError && onError();
|
||||
// reject(error);
|
||||
// });
|
||||
// });
|
||||
// };
|
||||
|
||||
const aliOssUpload = async (customRequestOptions: { file: File; }, callback?: (arg0: string | undefined) => any) => {
|
||||
await getOssPolicy();
|
||||
const { file } = customRequestOptions;
|
||||
// 生成随机文件名
|
||||
const getRandomFileName = () => {
|
||||
const randomNum = Math.floor(Math.random() * 10000);
|
||||
const timestamp = new Date().format('yyyyMMddhhmmss');
|
||||
const extension = file.name.split(".").pop();
|
||||
return `${policy.key}${timestamp}-${randomNum}.${extension}`;
|
||||
}
|
||||
|
||||
const client = new OSS({
|
||||
// yourRegion填写Bucket所在地域。以华东1(杭州)为例,yourRegion填写为oss-cn-hangzhou。
|
||||
region: policy.region,
|
||||
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
|
||||
accessKeyId: policy.keyId,
|
||||
accessKeySecret: policy.keySecret,
|
||||
// 从STS服务获取的安全令牌(SecurityToken)。
|
||||
stsToken: policy.token,
|
||||
// 填写Bucket名称。
|
||||
bucket: policy.bucket,
|
||||
});
|
||||
try {
|
||||
// 填写Object完整路径。Object完整路径中不能包含Bucket名称。
|
||||
// 您可以通过自定义文件名(例如exampleobject.txt)或文件完整路径(例如exampledir/exampleobject.txt)的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
|
||||
// data对象可以自定义为file对象、Blob数据或者OSS Buffer。
|
||||
const options = {
|
||||
meta: { temp: "demo" },
|
||||
mime: "json",
|
||||
headers: { "Content-Type": "text/plain" },
|
||||
};
|
||||
const result = await client.put(getRandomFileName(), file, options);
|
||||
let ppUrl = result?.url
|
||||
if(policy.cdnDomain){
|
||||
ppUrl = policy.cdnDomain + result.name
|
||||
}
|
||||
callback && callback(ppUrl);
|
||||
return Promise.resolve()
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
}
|
||||
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片校验
|
||||
* @param options
|
||||
*/
|
||||
const uploadImgBefore = (options: Options): Promise<boolean> => {
|
||||
const callBack = (flag: boolean) => {
|
||||
if (options.callBack) {
|
||||
options.callBack(flag);
|
||||
}
|
||||
};
|
||||
const getPercent = (num: number, total: number) => {
|
||||
num = parseFloat(num);
|
||||
total = parseFloat(total);
|
||||
if (isNaN(num) || isNaN(total)) {
|
||||
return "-";
|
||||
}
|
||||
return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00) + "%";
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const reader = new FileReader(); //通过FileReader类型读取文件中的数据(异步文件读取)
|
||||
reader.onload = (e) => {
|
||||
const data = e.target?.result; //返回文件框内上传的对象
|
||||
//加载图片获取图片真实宽度和高度
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
const width = image.width;
|
||||
const height = image.height;
|
||||
const flag: boolean =
|
||||
(options.type === "ratio" && getPercent(options.width, options.height) === getPercent(width, height))
|
||||
||
|
||||
(width === options.width && height === options.height);
|
||||
callBack(flag);
|
||||
return resolve(flag);
|
||||
};
|
||||
//img.src 应该是放在 onload 方法后边的, 因为当image的src发生改变,浏览器就会跑去加载这个src里的资源,先告诉浏览器图片加载完要怎么处理,再让它去加载图片
|
||||
image.src = data as string;
|
||||
};
|
||||
//读取文件并将文件数据以URL形式保存到result属性中。 读取图像常用
|
||||
reader.readAsDataURL(options.file);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
init();
|
||||
return { uploadImgBefore, getOssPolicy, getHeader, aliOssUpload };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router';
|
||||
import {useUserStore} from "@/store/modules/user";
|
||||
import {domainStoreWidthOut} from "@/store/modules/domain";
|
||||
import {getDomainList} from "@/api/login";
|
||||
|
||||
export const constantRouter: Array<RouteRecordRaw> = [
|
||||
{
|
||||
@@ -234,7 +236,15 @@ const router = createRouter({
|
||||
|
||||
|
||||
// @ts-ignore
|
||||
router.beforeEach((to, from, next) => {
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
const dsw = domainStoreWidthOut()
|
||||
if (!dsw.getDomain || dsw.getDomain.length == 0) {
|
||||
const response = await getDomainList()
|
||||
if (response && response.data) {
|
||||
const domain = response.data.split(',')
|
||||
dsw.setDomain(domain)
|
||||
}
|
||||
}
|
||||
if (to.meta.title) { // 判断是否有标题
|
||||
document.title = to.meta.title as string;
|
||||
}
|
||||
|
||||
43
src/store/modules/domain.ts
Normal file
43
src/store/modules/domain.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import {defineStore} from 'pinia';
|
||||
import {store} from '@/store';
|
||||
|
||||
export interface IDomain{
|
||||
domain: string[]
|
||||
}
|
||||
|
||||
export const domainStore = defineStore({
|
||||
id: 'domain',
|
||||
state: (): IDomain => ({
|
||||
domain: []
|
||||
}),
|
||||
getters:{
|
||||
getDomain(): string[] {
|
||||
return this.domain
|
||||
}
|
||||
},
|
||||
actions: {
|
||||
// async setDomain() {
|
||||
// let response = await getDomainList();
|
||||
// if (response && response.data) {
|
||||
// this.domain = response.data.split(',')
|
||||
// }
|
||||
// // getDomainList().then(response => {
|
||||
// // if(response && response.data){
|
||||
// // this.domain = response.data.split(',')
|
||||
// // }
|
||||
// // })
|
||||
// },
|
||||
setDomain(domain: string[]): void {
|
||||
this.domain = domain
|
||||
},
|
||||
// refreshDomain(){
|
||||
// if(!this.domain || this.domain.length == 0){
|
||||
// this.setDomain().then()
|
||||
// }
|
||||
// }
|
||||
}
|
||||
})
|
||||
|
||||
export function domainStoreWidthOut() {
|
||||
return domainStore(store);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { setObjToUrlParams } from '@/utils/urlUtils';
|
||||
import { RequestOptions, Result, CreateAxiosOptions } from './types';
|
||||
|
||||
import { useUserStoreWidthOut } from '@/store/modules/user';
|
||||
import {domainStoreWidthOut} from "@/store/modules/domain";
|
||||
|
||||
const urlPrefix = '';
|
||||
|
||||
@@ -38,6 +39,12 @@ const transform: AxiosTransform = {
|
||||
isReturnNativeResponse,
|
||||
} = options;
|
||||
|
||||
console.log(res.request.responseURL.endsWith('domain.txt'))
|
||||
console.log(res.request.responseURL)
|
||||
if(res.request.responseURL.includes('domain.txt')){
|
||||
return res;
|
||||
}
|
||||
|
||||
// 是否返回原生响应头 比如:需要获取响应头时使用该属性
|
||||
if (isReturnNativeResponse) {
|
||||
return res;
|
||||
@@ -122,16 +129,28 @@ const transform: AxiosTransform = {
|
||||
// 请求之前处理config
|
||||
beforeRequestHook: (config, options) => {
|
||||
const { apiUrl, joinPrefix, joinParamsToUrl, formatDate, joinTime = true, urlPrefix } = options;
|
||||
|
||||
const isUrlStr = isUrl(config.url as string);
|
||||
|
||||
if (!isUrlStr && joinPrefix) {
|
||||
config.url = `${urlPrefix}${config.url}`;
|
||||
}
|
||||
|
||||
if (!isUrlStr && apiUrl && isString(apiUrl)) {
|
||||
config.url = `${apiUrl}${config.url}`;
|
||||
if(!isUrlStr){
|
||||
let domain = domainStoreWidthOut().getDomain;
|
||||
if(config.url && config.url.endsWith("domain.txt")){
|
||||
return config
|
||||
}else if(domain && domain.length > 0){
|
||||
let domainUrl = domain[Math.floor((Math.random()*domain.length))];
|
||||
config.url = domainUrl + config.url;
|
||||
}else if(apiUrl && isString(apiUrl)){
|
||||
config.url = `${apiUrl}${config.url}`;
|
||||
}
|
||||
}else{
|
||||
if(config.url && config.url.endsWith("domain.txt")){
|
||||
return config
|
||||
}
|
||||
}
|
||||
// if (!isUrlStr && apiUrl && isString(apiUrl)) {
|
||||
// config.url = `${apiUrl}${config.url}`;
|
||||
// }
|
||||
const params = config.params || {};
|
||||
const data = config.data || false;
|
||||
if (config.method?.toUpperCase() === RequestEnum.GET) {
|
||||
@@ -258,7 +277,8 @@ function createAxios(opt?: Partial<CreateAxiosOptions>) {
|
||||
// 消息提示类型
|
||||
errorMessageMode: 'none',
|
||||
// 接口地址
|
||||
apiUrl: 'http://101.32.189.213:2781',
|
||||
// apiUrl: 'https://fhusdbs.vbg2c.top',
|
||||
apiUrl: '',
|
||||
// apiUrl: '',
|
||||
// 接口拼接地址
|
||||
urlPrefix: urlPrefix,
|
||||
|
||||
@@ -110,7 +110,7 @@ import {debounce, getAssetsImages, px2vw} from "@/utils";
|
||||
import {computed, onMounted, reactive, ref,onUnmounted} from "vue";
|
||||
import {useRouter} from "vue-router";
|
||||
import {useUserStore} from "@/store/modules/user";
|
||||
import {getCalLoan, getHomeInfo, getLoansInfo, getLoansUser, getUserInfo} from "@/api";
|
||||
import {getCalLoan, getHomeInfo, getLoansInfo, getLoansUser, getOssPolicyInfo, getUserInfo} from "@/api";
|
||||
import {resetData} from "@/utils/dataUtil";
|
||||
import {watch} from "vue-demi";
|
||||
import {showToast} from "vant";
|
||||
@@ -265,11 +265,19 @@ const _getUserInfo = () => {
|
||||
resetData(userInfo, res)
|
||||
})
|
||||
}
|
||||
|
||||
const _getSts = () => {
|
||||
getOssPolicyInfo().then(res => {
|
||||
console.log('res', res)
|
||||
})
|
||||
|
||||
}
|
||||
onMounted(() => {
|
||||
_getLoansInfo()
|
||||
_getHomeInfo()
|
||||
_getLoansUser()
|
||||
_getUserInfo()
|
||||
_getSts()
|
||||
})
|
||||
onUnmounted(() => {
|
||||
clearInterval(timer.value);
|
||||
|
||||
@@ -118,6 +118,7 @@ import {resetData} from "@/utils/dataUtil";
|
||||
import {getAssetsImages, px2vw} from "@/utils";
|
||||
import {showToast} from "vant";
|
||||
import {useRouter} from "vue-router";
|
||||
import {useUpload} from "@/hooks/useUpload";
|
||||
|
||||
const idCardKeyboardShow = ref(false)
|
||||
|
||||
@@ -179,14 +180,22 @@ const afterReadIdBack = (file) => {
|
||||
upLoadImage(file, 'cardFrontPicture')
|
||||
};
|
||||
|
||||
const upload = useUpload()
|
||||
|
||||
const upLoadImage = (file, flag) => {
|
||||
uploadCommon(file.file).then(res => {
|
||||
if (res.data.code == 200) {
|
||||
userInfo[flag] = res.data.data.url
|
||||
} else {
|
||||
showToast('上传失败');
|
||||
}
|
||||
|
||||
upload.aliOssUpload(file, url => {
|
||||
console.log(url)
|
||||
userInfo[flag] = url
|
||||
})
|
||||
|
||||
// uploadCommon(file.file).then(res => {
|
||||
// if (res.data.code == 200) {
|
||||
// userInfo[flag] = res.data.data.url
|
||||
// } else {
|
||||
// showToast('上传失败');
|
||||
// }
|
||||
// })
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
Reference in New Issue
Block a user