| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390 |
- import { UPLOAD_URL } from '@/settings/siteSetting.js';
- import { useUserStore } from '@/store/user.js';
- const userStore = useUserStore();
- /**
- * type // image / video / file
- * opts {
- dir 上传路径
- filePath 文件资源
- count // 默认 1
- }
- **/
- let APIURLSET = uni.getStorageSync('APIURL')
- let APIURL = UPLOAD_URL
- if (APIURLSET) APIURL = `${String(APIURLSET).replace(/\/$/, '')}/file/upload`;
- export function chooseAndUploadFile(type, opts, dir = '') {
- if (type === 'image') {
- chooseImage({
- dir,
- ...opts
- });
- } else if (type === 'video') {
- chooseVideo({
- dir,
- ...opts
- });
- } else if (type === 'audio' || type === 'voice') {
- chooseAudio({
- dir,
- ...opts
- });
- } else {
- chooseFile({
- dir,
- ...opts
- });
- }
- }
- // 选择图片
- function chooseImage(opts = {}) {
- const { count = 1, sizeType = ['original'], sourceType = ['album', 'camera'], extension = ['gif', 'jpg', 'jpeg', 'png', 'bmp', 'webp'], callBack } = opts;
- uni.chooseImage({
- count,
- sizeType,
- extension,
- sourceType,
- success: async (res) => {
- console.log('chooseImage res res', res);
- const tempFiles = res.tempFiles;
- const file = await batchUploadFile({
- files: tempFiles,
- ...opts
- });
- console.log('file', file);
- callBack && callBack(file);
- },
- fail: (err) => {
- console.log('chooseImage-fail', err);
- }
- });
- }
- // 选择文件
- function chooseFile(opts = {}) {
- const { count = 1 } = opts;
- wx.chooseMessageFile({
- type: 'file',
- count,
- success: async (res) => {
- const { tempFiles } = res;
- const file = await batchUploadFile({
- files: tempFiles,
- ...opts
- });
- console.log('file', file);
- },
- fail(error) {
- console.log('fail', error);
- }
- });
- }
- // 选择视频
- function chooseVideo(opts = {}) {
- const { sourceType, callBack, dir, compressed = false, isVideo = false } = opts;
- // console.log('compressed', compressed);
- uni.chooseVideo({
- sourceType,
- compressed,
- success: async (res) => {
- const { size, tempFilePath } = res;
- let videoMaxSize = 300;
- if (userStore.getDefaultConfig) videoMaxSize = userStore.getDefaultConfig.videoMaxSize;
- // console.log('232333', videoMaxSize, size, userStore.getDefaultConfig);
- if (size > 1024 * 1024 * videoMaxSize) {
- uni.showModal({
- title: `视频需要${videoMaxSize}M以内`,
- success: (res) => {}
- });
- return;
- }
- const url = await uploadFile({
- dir,
- filePath: tempFilePath,
- isVideo,
- size: size ? (size / 1024 / 1024).toFixed(2) : 0
- });
- uni.setStorageSync('videoUrlUp', tempFilePath);
- callBack && callBack(url);
- // uni.compressVideo({
- // src: res.tempFilePath,
- // quality: 'high',
- // success: async (ress) => {
- // // 压缩成功
- // console.log('压缩成功', ress);
- // const { size, tempFilePath } = ress;
- // const url = await uploadFile({
- // dir,
- // filePath: tempFilePath
- // });
- // callBack && callBack(url);
- // },
- // fail: async (err) => {
- // // 压缩失败
- // console.log('压缩失败', err);
- // const { size, tempFilePath } = res;
- // const url = await uploadFile({
- // dir,
- // filePath: tempFilePath
- // });
- // callBack && callBack(url);
- // }
- // });
- // console.log('chooseVideo res res', res);
- },
- fail: (err) => {
- console.log('chooseVideo-fail', err);
- }
- });
- }
- // 选择音频
- function chooseAudio(opts = {}) {
- const { dir, callBack } = opts;
- wx.chooseMessageFile({
- count: 1,
- type: 'file',
- extension: ['mp3', 'wav', 'aac', 'ogg', 'wma', 'alac', 'amr', 'm4a'],
- success: async (res) => {
- console.log('chooseAudio res res', res.tempFiles[0].path);
- if (
- res.tempFiles[0].path.indexOf('.mp3') == -1 &&
- res.tempFiles[0].path.indexOf('.m4a') == -1 &&
- res.tempFiles[0].path.indexOf('.wav') == -1 &&
- res.tempFiles[0].path.indexOf('.MP3') == -1 &&
- res.tempFiles[0].path.indexOf('.M4A') == -1 &&
- res.tempFiles[0].path.indexOf('.WAV') == -1 &&
- res.tempFiles[0].path.indexOf('.aac') == -1 &&
- res.tempFiles[0].path.indexOf('.AAC') == -1 &&
- res.tempFiles[0].path.indexOf('.ogg') == -1 &&
- res.tempFiles[0].path.indexOf('.OGG') == -1 &&
- res.tempFiles[0].path.indexOf('.wma') == -1 &&
- res.tempFiles[0].path.indexOf('.WMA') == -1 &&
- res.tempFiles[0].path.indexOf('.alac') == -1 &&
- res.tempFiles[0].path.indexOf('.ALAC') == -1 &&
- res.tempFiles[0].path.indexOf('.amr') == -1 &&
- res.tempFiles[0].path.indexOf('.AMR') == -1
- ) {
- uni.showToast({
- title: '音频格式只能是mp3/m4a/wav',
- icon: 'none'
- });
- return;
- }
- const { tempFiles } = res;
- // if (tempFiles[0].size / 1024 / 1024 > 35) {
- // uni.showToast({ icon: 'none', mask: true, title: '音频需要35M以内' });
- // return;
- // }
- const url = await uploadFile({
- dir,
- filePath: tempFiles[0].path,
- size: tempFiles[0].size ? (tempFiles[0].size / 1024 / 1024).toFixed(2) : 0
- });
- callBack && callBack(url);
- },
- fail: (err) => {
- console.log('chooseAudio-fail', err);
- }
- });
- }
- // 上传之前
- function beforeUnload(files) {
- return new Promise(async (resolve, reject) => {
- const filesSize = files.map((x) => x.size / 1024 / 1024);
- const isExceed = filesSize.some((x) => x > 8);
- if (isExceed && files.length === 1) {
- uni.showToast({ icon: 'none', mask: true, title: '文件需要8M以内' });
- } else if (isExceed && files.length > 1) {
- files = files.filter((x) => x.size / 1024 / 1024 < 8);
- uni.showModal({
- title: '提示',
- content: '部分文件超过8M 已过滤,是否继续上传',
- confirmText: '继续上传',
- success: (res) => {
- if (res.confirm) {
- resolve(files);
- }
- }
- });
- } else {
- resolve(files);
- }
- });
- }
- // 批量上传
- export const batchUploadFile = async (opts = {}) => {
- const { dir = '', files } = opts;
- const fileFilter = await beforeUnload(files);
- let index = 0,
- filesLength = fileFilter.length,
- urls = [],
- errorArr = [];
- return new Promise(async (resolve, reject) => {
- let header = {
- 'Content-Type': 'application/json;charset=UTF-8',
- userId: userStore.getSiteId,
- Authorization: userStore.getToken
- };
- uni.showLoading({ mask: true, title: '上传中' });
- let str = dir ? '?typeId=' + dir : '';
- const startUpload = () => {
- return new Promise((resolve, reject) => {
- let start = () => {
- uni.uploadFile({
- url: APIURL + str,
- name: 'file',
- header,
- timeout: 1000 * 60 * 5,
- filePath: fileFilter[index].path,
- success: (res) => {
- console.log('uploadFile res', res);
- if (res.statusCode === 200) {
- const { data } = res;
- const jsonData = JSON.parse(data);
- console.log('jsonData', jsonData);
- if (jsonData.code == -3){
- uni.hideLoading()
- uni.showModal({
- title: '请先登录',
- success: (res) => {
- if (res.confirm) {
- uni.redirectTo({
- url: '/pages/index/index'
- });
- }
- },
- });
- return
- }
- if (jsonData.count === 0) {
- const { relativePath } = jsonData.data;
- urls.push(relativePath);
- index++;
- if (index >= filesLength) {
- resolve(true);
- } else {
- setTimeout(() => {
- start();
- }, 200);
- }
- } else {
- index++;
- }
- } else {
- index++;
- setTimeout(() => {
- uni.showModal({
- title: '上传失败',
- success: (res) => {}
- });
- }, 500);
- }
- }
- });
- };
- start();
- });
- };
- const flag = await startUpload();
- if (flag) {
- uni.hideLoading();
- // setTimeout(() => {
- // uni.showModal({
- // title: '上传失败',
- // success: (res) => {}
- // });
- // }, 500);
- resolve(urls);
- } else {
- reject(null);
- }
- });
- };
- // 上传
- export const uploadFile = (params = {}) => {
- const { dir = '', filePath, isVideo, size = '' } = params;
- let header = {
- 'Content-Type': 'application/json;charset=UTF-8',
- userId: userStore.getSiteId,
- Authorization: userStore.getToken
- };
- let sizeMsg = size ? `当前文件大小${size}M` : '';
- return new Promise((resolve, reject) => {
- if (!isVideo) uni.showLoading({ mask: true, title: '上传中' });
- let str = dir ? '?typeId=' + dir : '';
- let uploadTask = uni.uploadFile({
- url: APIURL + str,
- name: 'file',
- filePath,
- header,
- timeout: 1000 * 60 * 10,
- success: (res) => {
- if (res.statusCode === 200) {
- const { data } = res;
- const jsonData = JSON.parse(data);
- console.log('uploadFile.jsonData', jsonData);
- if (jsonData.code == 1) {
- const { relativePath } = jsonData.data;
- resolve(relativePath);
- } else {
- uni.showModal({
- title: jsonData.msg,
- success: (res) => {}
- });
- reject(new Error(jsonData.msg || '上传失败'));
- }
- } else {
- setTimeout(() => {
- uni.showModal({
- title: `接口错误!请重新上传!${sizeMsg}`,
- success: (res) => {}
- });
- }, 500);
- reject(new Error('接口错误'));
- }
- },
- fail: (err) => {
- setTimeout(() => {
- uni.showModal({
- title: `上传超时 ${sizeMsg}`,
- success: (res) => {}
- });
- }, 500);
- reject(err || new Error('上传失败'));
- },
- complete: () => {
- uni.hideLoading();
- }
- });
- uploadTask.onProgressUpdate((res) => {
- let progressText = '上传进度:' + res.progress + '%';
- if (res.progress === 100) {
- progressText = '上传完成';
- setTimeout(() => {
- progressText = '';
- }, 1500);
- }
- if (isVideo) {
- userStore.setUploadProgress(progressText);
- } else {
- uni.showLoading({ mask: true, title: progressText });
- }
- });
- });
- };
|