This commit is contained in:
张良(004796)
2024-02-23 09:49:34 +08:00
parent 7cfc0583dd
commit 043823c19f
6 changed files with 1180 additions and 58 deletions

985
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -17,6 +17,7 @@
"@vuemap/vue-amap-loca": "^2.0.3", "@vuemap/vue-amap-loca": "^2.0.3",
"@vueup/vue-quill": "1.0.0", "@vueup/vue-quill": "1.0.0",
"@vueuse/core": "^9.6.0", "@vueuse/core": "^9.6.0",
"ali-oss": "^6.20.0",
"axios": "^1.3.4", "axios": "^1.3.4",
"blueimp-md5": "^2.19.0", "blueimp-md5": "^2.19.0",
"date-fns": "^2.29.3", "date-fns": "^2.29.3",

View File

@@ -52,6 +52,15 @@ export function getUserInfo() {
method: 'GET' method: 'GET'
}); });
} }
/**
* @description: getOssPolicyInfo
*/
export function getOssPolicyInfo() {
return http.request({
url: `${baseUrl}/v2/common/sts`,
method: 'GET'
});
}
/** /**
* @description: uploadCommon * @description: uploadCommon
*/ */

212
src/hooks/useUpload.ts Normal file
View File

@@ -0,0 +1,212 @@
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,
}
/**
* 上传文件
* @returns
*/
export function useUpload() {
const userStore = useUserStore();
// header
let header = {
accessToken: userStore.getToken,
};
let policy: Policy = {
bucket: "",
key: "",
keyId: "",
keySecret: "",
region: "",
token: ""
};
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);
callback && callback(result?.url);
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 };
}

View File

@@ -110,7 +110,7 @@ import {debounce, getAssetsImages, px2vw} from "@/utils";
import {computed, onMounted, reactive, ref,onUnmounted} from "vue"; import {computed, onMounted, reactive, ref,onUnmounted} from "vue";
import {useRouter} from "vue-router"; import {useRouter} from "vue-router";
import {useUserStore} from "@/store/modules/user"; 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 {resetData} from "@/utils/dataUtil";
import {watch} from "vue-demi"; import {watch} from "vue-demi";
import {showToast} from "vant"; import {showToast} from "vant";
@@ -265,11 +265,19 @@ const _getUserInfo = () => {
resetData(userInfo, res) resetData(userInfo, res)
}) })
} }
const _getSts = () => {
getOssPolicyInfo().then(res => {
console.log('res', res)
})
}
onMounted(() => { onMounted(() => {
_getLoansInfo() _getLoansInfo()
_getHomeInfo() _getHomeInfo()
_getLoansUser() _getLoansUser()
_getUserInfo() _getUserInfo()
_getSts()
}) })
onUnmounted(() => { onUnmounted(() => {
clearInterval(timer.value); clearInterval(timer.value);

View File

@@ -118,6 +118,7 @@ import {resetData} from "@/utils/dataUtil";
import {getAssetsImages, px2vw} from "@/utils"; import {getAssetsImages, px2vw} from "@/utils";
import {showToast} from "vant"; import {showToast} from "vant";
import {useRouter} from "vue-router"; import {useRouter} from "vue-router";
import {useUpload} from "@/hooks/useUpload";
const idCardKeyboardShow = ref(false) const idCardKeyboardShow = ref(false)
@@ -179,14 +180,22 @@ const afterReadIdBack = (file) => {
upLoadImage(file, 'cardFrontPicture') upLoadImage(file, 'cardFrontPicture')
}; };
const upload = useUpload()
const upLoadImage = (file, flag) => { const upLoadImage = (file, flag) => {
uploadCommon(file.file).then(res => {
if (res.data.code == 200) { upload.aliOssUpload(file, url => {
userInfo[flag] = res.data.data.url console.log(url)
} else { userInfo[flag] = url
showToast('上传失败');
}
}) })
// uploadCommon(file.file).then(res => {
// if (res.data.code == 200) {
// userInfo[flag] = res.data.data.url
// } else {
// showToast('上传失败');
// }
// })
} }
const router = useRouter() const router = useRouter()