Commit 72bdeb1c by cen

fix: oss上传

1 parent da95b8da
...@@ -509,7 +509,7 @@ Page({ ...@@ -509,7 +509,7 @@ Page({
// 如果是检测报告,添加额外字段 // 如果是检测报告,添加额外字段
if (fileType === 5) { if (fileType === 5) {
// 根据文件扩展名确定格式 // 根据文件扩展名确定格式
const ext = image.url.split(".").pop().toLowerCase(); const ext = image.url.split("?")[0].split(".").pop().toLowerCase();
fileItem.fileFormat = ext === "jpg" || ext === "jpeg" ? "jpg" : ext; fileItem.fileFormat = ext === "jpg" || ext === "jpeg" ? "jpg" : ext;
fileItem.fileName = image.name || this.getImageNameByKey(keyNum); fileItem.fileName = image.name || this.getImageNameByKey(keyNum);
} }
...@@ -880,10 +880,15 @@ Page({ ...@@ -880,10 +880,15 @@ Page({
// 处理详情数据 // 处理详情数据
handleDetailData(data, evalOrderNo) { handleDetailData(data, evalOrderNo) {
const { basic = {}, carInfo = {}, carLicense = {}, images } = data; const { basic = {}, carInfo = {}, carLicense = {}, images } = data;
// 确保 images 是数组,如果为 null 或 undefined,设置为空数组 // 确保 images 是数组,如果为 null 或 undefined,设置为空数组
const imageList = Array.isArray(images) ? images : []; const imageList = Array.isArray(images) ? images : [];
console.log("handleDetailData - 原始 images:", images, "处理后:", imageList); console.log(
"handleDetailData - 原始 images:",
images,
"处理后:",
imageList
);
// 处理地区显示格式:确保是 "省份 城市" 格式 // 处理地区显示格式:确保是 "省份 城市" 格式
// 车辆所在地 // 车辆所在地
......
<!-- packageUsedCar/pages/evaluationForm/components/ThirdStep/ThirdStep.wxml --> <!-- packageUsedCar/pages/evaluationForm/components/ThirdStep/ThirdStep.wxml -->
<wxs module="utils"> <wxs module="utils">
// 获取视频封面图 URL:优先 coverUrl,其次 OSS 视频用 snapshot 生成,否则用默认图
var getVideoCoverUrl = function(videoUrl, coverUrl, defaultImg) {
if (coverUrl && coverUrl !== '' && coverUrl.indexOf('.mp4') === -1 && coverUrl.indexOf('.mov') === -1 && coverUrl.indexOf('.avi') === -1) {
return coverUrl;
}
if (videoUrl && videoUrl.indexOf('aliyuncs.com') !== -1) {
var sep = videoUrl.indexOf('?') >= 0 ? '&' : '?';
return videoUrl + sep + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast';
}
return defaultImg || '';
};
// 判断 coverUrl 是否有效(不能是视频文件 URL) // 判断 coverUrl 是否有效(不能是视频文件 URL)
var hasValidCoverUrl = function(coverUrl) { var hasValidCoverUrl = function(coverUrl) {
if (!coverUrl || coverUrl === '' || coverUrl === 'undefined' || coverUrl === 'null') { if (!coverUrl || coverUrl === '' || coverUrl === 'undefined' || coverUrl === 'null') {
...@@ -90,7 +102,8 @@ ...@@ -90,7 +102,8 @@
module.exports = { module.exports = {
getUploadText: getUploadText, getUploadText: getUploadText,
getDoneCount: getDoneCount, getDoneCount: getDoneCount,
hasValidCoverUrl: hasValidCoverUrl hasValidCoverUrl: hasValidCoverUrl,
getVideoCoverUrl: getVideoCoverUrl
}; };
</wxs> </wxs>
<view class="thirdStep"> <view class="thirdStep">
...@@ -156,8 +169,7 @@ ...@@ -156,8 +169,7 @@
<view wx:if="{{ !subItem.status || subItem.status === 'done' }}" class="uploaded-image-container"> <view wx:if="{{ !subItem.status || subItem.status === 'done' }}" class="uploaded-image-container">
<!-- 视频 --> <!-- 视频 -->
<view wx:if="{{ subItem.isVideo }}" class="video-container" bindtap="previewVideoMedia" data-key="{{ item.key }}" data-file-url="{{ subItem.url }}"> <view wx:if="{{ subItem.isVideo }}" class="video-container" bindtap="previewVideoMedia" data-key="{{ item.key }}" data-file-url="{{ subItem.url }}">
<image wx:if="{{ utils.hasValidCoverUrl(subItem.coverUrl) }}" src="{{ subItem.coverUrl }}" mode="aspectFit"></image> <image src="{{ utils.getVideoCoverUrl(subItem.url, subItem.coverUrl, IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFit"></image>
<image wx:else src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFit"></image>
<view class="video-play-icon"> <view class="video-play-icon">
<image src="{{ IMG_URL }}usedCar/upload-play.png" class="icon-upload-play"></image> <image src="{{ IMG_URL }}usedCar/upload-play.png" class="icon-upload-play"></image>
</view> </view>
......
...@@ -25,25 +25,53 @@ ...@@ -25,25 +25,53 @@
lower.indexOf('.mov') !== -1; lower.indexOf('.mov') !== -1;
}; };
// 分割逗号分隔的URL字符串 var getVideoCoverUrl = function(videoUrl, defaultImg) {
if (videoUrl && videoUrl.indexOf('aliyuncs.com') !== -1) {
var sep = videoUrl.indexOf('?') >= 0 ? '&' : '?';
return videoUrl + sep + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast';
}
return defaultImg || '';
};
// 分割逗号分隔的URL字符串(OSS参数内也有逗号,只在逗号后紧跟http时拆分)
var splitUrls = function(urlString) { var splitUrls = function(urlString) {
if (!urlString || typeof urlString !== 'string') return []; if (!urlString || typeof urlString !== 'string') return [];
var urls = urlString.split(',');
var result = []; var result = [];
for (var i = 0; i < urls.length; i++) { var sep1 = ',https://';
var url = urls[i].trim(); var sep2 = ',http://';
if (url) { var remaining = urlString.trim();
result.push(url); while (remaining) {
var idx1 = remaining.indexOf(sep1);
var idx2 = remaining.indexOf(sep2);
var idx = -1;
var nextUrl = '';
if (idx1 >= 0 && idx2 >= 0) {
idx = idx1 < idx2 ? idx1 : idx2;
nextUrl = idx1 < idx2 ? 'https://' : 'http://';
} else if (idx1 >= 0) {
idx = idx1;
nextUrl = 'https://';
} else if (idx2 >= 0) {
idx = idx2;
nextUrl = 'http://';
}
if (idx >= 0) {
result.push(remaining.substring(0, idx).trim());
remaining = nextUrl + remaining.substring(idx + nextUrl.length);
} else {
result.push(remaining.trim());
break;
} }
} }
return result; return result.filter(function(u) { return u; });
}; };
module.exports = { module.exports = {
formatType: formatType, formatType: formatType,
isVideo: isVideo, isVideo: isVideo,
isMedia: isMedia, isMedia: isMedia,
splitUrls: splitUrls splitUrls: splitUrls,
getVideoCoverUrl: getVideoCoverUrl
}; };
</wxs> </wxs>
<popup show="{{show}}" title="{{title }}" height="{{height}}" bindconfirm="onConfirm" bindcancel="onCancel" singleButton="{{singleButton}}" confirmText="{{confirmText}}"> <popup show="{{show}}" title="{{title }}" height="{{height}}" bindconfirm="onConfirm" bindcancel="onCancel" singleButton="{{singleButton}}" confirmText="{{confirmText}}">
...@@ -65,7 +93,7 @@ ...@@ -65,7 +93,7 @@
<view wx:if="{{utils.isMedia(item.fieldBeforeValue)}}" class="media-list"> <view wx:if="{{utils.isMedia(item.fieldBeforeValue)}}" class="media-list">
<block wx:for="{{utils.splitUrls(item.fieldBeforeValue)}}" wx:key="*this" wx:for-item="url" wx:for-index="urlIdx"> <block wx:for="{{utils.splitUrls(item.fieldBeforeValue)}}" wx:key="*this" wx:for-item="url" wx:for-index="urlIdx">
<view wx:if="{{utils.isVideo(url)}}" class="media-box video" bindtap="onPreview" data-url="{{url}}" data-type="video"> <view wx:if="{{utils.isVideo(url)}}" class="media-box video" bindtap="onPreview" data-url="{{url}}" data-type="video">
<image class="media-img" src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFill" /> <image class="media-img" src="{{ utils.getVideoCoverUrl(url, IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFill" />
<view class="play-icon"></view> <view class="play-icon"></view>
</view> </view>
<view wx:else class="media-box" bindtap="onPreview" data-url="{{url}}" data-type="image"> <view wx:else class="media-box" bindtap="onPreview" data-url="{{url}}" data-type="image">
...@@ -86,7 +114,7 @@ ...@@ -86,7 +114,7 @@
<view wx:if="{{utils.isMedia(item.fieldAfterValue)}}" class="media-list"> <view wx:if="{{utils.isMedia(item.fieldAfterValue)}}" class="media-list">
<block wx:for="{{utils.splitUrls(item.fieldAfterValue)}}" wx:key="*this" wx:for-item="url" wx:for-index="urlIdx"> <block wx:for="{{utils.splitUrls(item.fieldAfterValue)}}" wx:key="*this" wx:for-item="url" wx:for-index="urlIdx">
<view wx:if="{{utils.isVideo(url)}}" class="media-box video" bindtap="onPreview" data-url="{{url}}" data-type="video"> <view wx:if="{{utils.isVideo(url)}}" class="media-box video" bindtap="onPreview" data-url="{{url}}" data-type="video">
<image class="media-img" src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFill" /> <image class="media-img" src="{{ utils.getVideoCoverUrl(url, IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFill" />
<view class="play-icon"></view> <view class="play-icon"></view>
</view> </view>
<view wx:else class="media-box" bindtap="onPreview" data-url="{{url}}" data-type="image"> <view wx:else class="media-box" bindtap="onPreview" data-url="{{url}}" data-type="image">
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
const IMG_URL = "https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/" const IMG_URL = "https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/"
import dayjs from 'dayjs' import dayjs from 'dayjs'
import api from '~/api/api.js' import api from '~/api/api.js'
import { uploadFile } from '~/utils/oss/ossUpload.js'
import newApi from '~/packageUsedCar/api' import newApi from '~/packageUsedCar/api'
import mapApi from "~/utils/mapapi/mapapi"; import mapApi from "~/utils/mapapi/mapapi";
Page({ Page({
...@@ -243,30 +244,17 @@ Page({ ...@@ -243,30 +244,17 @@ Page({
wx.$util.showLoading('上传中') wx.$util.showLoading('上传中')
try { try {
for (const item of tempFiles) { for (const item of tempFiles) {
const val = item.path const fileObj = {
const imgType = val.split('.')[1] tempFilePath: item.path || item.tempFilePath,
const upType = imgType === 'unknown' ? 'jpg' : imgType url: item.path || item.tempFilePath,
const _res = await new Promise((resolve, reject) => { size: item.size,
wx.getFileSystemManager().readFile({
filePath: val, // 选择图片返回的相对路径
encoding: 'base64', // 编码格式
success: resolve,
fail: reject
})
})
const img = await api.uploadImg({
file: `${upType}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
_this.data[type][index].uploadImages?.push({url: data, isVideo: false})
_this.setData({
[`${type}`]: _this.data[type],
[`formData.${field.key}`]: _this.data[type][index].uploadImages?.map(val => { return val.url })?.join(',')
})
} else {
wx.$util.showToast(message)
} }
const url = await uploadFile(fileObj)
_this.data[type][index].uploadImages?.push({url, isVideo: false})
_this.setData({
[`${type}`]: _this.data[type],
[`formData.${field.key}`]: _this.data[type][index].uploadImages?.map(val => val.url)?.join(',')
})
} }
} catch (error) { } catch (error) {
wx.$util.showToast("上传失败,请重试") wx.$util.showToast("上传失败,请重试")
...@@ -297,30 +285,18 @@ Page({ ...@@ -297,30 +285,18 @@ Page({
wx.$util.showLoading('上传中') wx.$util.showLoading('上传中')
try { try {
for (const item of tempFiles) { for (const item of tempFiles) {
const val = item.tempFilePath const fileObj = {
const imgType = val.split('.')[1] tempFilePath: item.tempFilePath || item.path,
const upType = imgType === 'unknown' ? 'jpg' : imgType url: item.tempFilePath || item.path,
const _res = await new Promise((resolve, reject) => { size: item.size,
wx.getFileSystemManager().readFile({
filePath: val, // 选择图片返回的相对路径
encoding: 'base64', // 编码格式
success: resolve,
fail: reject
})
})
const img = await api.uploadFileWithCover({
file: `${upType}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
_this.data[type][index].uploadImages?.push({url: data.videoUrl, isVideo: true, coverUrl: data.coverUrl})
_this.setData({
[`${type}`]: _this.data[type],
[`formData.${field.key}`]: data.videoUrl
})
} else {
wx.$util.showToast(message)
} }
const videoUrl = await uploadFile(fileObj)
const coverUrl = videoUrl + '&x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
_this.data[type][index].uploadImages?.push({url: videoUrl, isVideo: true, coverUrl})
_this.setData({
[`${type}`]: _this.data[type],
[`formData.${field.key}`]: videoUrl
})
} }
} catch (error) { } catch (error) {
wx.$util.showToast("上传失败,请重试") wx.$util.showToast("上传失败,请重试")
...@@ -367,35 +343,22 @@ Page({ ...@@ -367,35 +343,22 @@ Page({
wx.$util.showLoading('上传中') wx.$util.showLoading('上传中')
try { try {
for (const item of tempFiles) { for (const item of tempFiles) {
const val = item.tempFilePath const fileObj = {
const imgType = val.split('.')[1] tempFilePath: item.tempFilePath || item.path,
const uploadType = imgType === 'unknown' ? 'jpg' : imgType url: item.tempFilePath || item.path,
const _res = await new Promise((resolve, reject) => { size: item.size,
wx.getFileSystemManager().readFile({ }
filePath: val, // 选择图片返回的相对路径 const url = await uploadFile(fileObj)
encoding: 'base64', // 编码格式 if (fileType == 'video') {
success: resolve, const coverUrl = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
fail: reject _this.data[type][index].uploadImages?.push({url, isVideo: true, coverUrl})
})
})
const img = await api[requestEvent]({
file: `${uploadType}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
if (fileType == 'video') {
_this.data[type][index].uploadImages?.push({url: data.videoUrl, isVideo: true, coverUrl: data.coverUrl})
} else {
_this.data[type][index].uploadImages?.push({url: data, isVideo: false})
}
_this.setData({
[`${type}`]: _this.data[type],
[`formData.${field.key}`]: fileType == 'video' ? data.videoUrl : _this.data[type][index].uploadImages?.map(val => { return val.url })?.join(',')
})
} else { } else {
wx.hideLoading() _this.data[type][index].uploadImages?.push({url, isVideo: false})
wx.$util.showToast(message)
} }
_this.setData({
[`${type}`]: _this.data[type],
[`formData.${field.key}`]: fileType == 'video' ? url : _this.data[type][index].uploadImages?.map(val => val.url)?.join(',')
})
} }
} catch (error) { } catch (error) {
wx.$util.showToast("上传失败,请重试") wx.$util.showToast("上传失败,请重试")
......
<!--packageUsedCar/pages/evaluationForm/confirmCar/confirmCar.wxml--> <!--packageUsedCar/pages/evaluationForm/confirmCar/confirmCar.wxml-->
<wxs module="utils">
var getVideoCoverUrl = function(videoUrl, coverUrl, defaultImg) {
if (coverUrl && coverUrl !== '' && coverUrl.indexOf('.mp4') === -1 && coverUrl.indexOf('.mov') === -1 && coverUrl.indexOf('.avi') === -1) {
return coverUrl;
}
if (videoUrl && videoUrl.indexOf('aliyuncs.com') !== -1) {
var sep = videoUrl.indexOf('?') >= 0 ? '&' : '?';
return videoUrl + sep + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast';
}
return defaultImg || '';
};
module.exports = { getVideoCoverUrl: getVideoCoverUrl };
</wxs>
<glsx-privacy appletName="生意助手员工版" bind:agreeClick="agreeClick" bind:disagreeClick="disagreeClick"></glsx-privacy> <glsx-privacy appletName="生意助手员工版" bind:agreeClick="agreeClick" bind:disagreeClick="disagreeClick"></glsx-privacy>
<view class="confirm-car"> <view class="confirm-car">
<navigation-bar class="navigation-header" bindnavbarReady="navbarReady" showBack navStyle="{{'background-color: rgba(0,0,0,0);box-shadow:none;' }}" bindback="back"> <navigation-bar class="navigation-header" bindnavbarReady="navbarReady" showBack navStyle="{{'background-color: rgba(0,0,0,0);box-shadow:none;' }}" bindback="back">
...@@ -30,7 +43,7 @@ ...@@ -30,7 +43,7 @@
<!-- 视频 --> <!-- 视频 -->
<view wx:if="{{subItem.isVideo}}" class="video-container" <view wx:if="{{subItem.isVideo}}" class="video-container"
bindtap="previewMedia" data-media="{{item.uploadImages}}"> bindtap="previewMedia" data-media="{{item.uploadImages}}">
<image src="{{subItem.coverUrl}}" mode="aspectFit"></image> <image src="{{utils.getVideoCoverUrl(subItem.url, subItem.coverUrl, IMG_URL + 'usedCar/video_default.png')}}" mode="aspectFit"></image>
<view class="video-play-icon"> <view class="video-play-icon">
<image src="{{IMG_URL}}usedCar/upload-play.png" class="icon-upload-play"></image> <image src="{{IMG_URL}}usedCar/upload-play.png" class="icon-upload-play"></image>
</view> </view>
......
...@@ -182,7 +182,7 @@ Page({ ...@@ -182,7 +182,7 @@ Page({
{ {
label: "营业执照图片", label: "营业执照图片",
key: "signingInfo.saleContract.orgLicenseUrl", key: "signingInfo.saleContract.orgLicenseUrl",
type: "imageArr" type: "imageArr",
}, },
{ {
label: "三方/委托交易凭证", label: "三方/委托交易凭证",
...@@ -556,8 +556,8 @@ Page({ ...@@ -556,8 +556,8 @@ Page({
if (type === 1 || type === "1") { if (type === 1 || type === "1") {
// 图片预览 // 图片预览
wx.previewImage({ wx.previewImage({
current: !((index ?? '') === '') ? url[index] : url, current: !((index ?? "") === "") ? url[index] : url,
urls: !((index ?? '') === '') ? url : [url], urls: !((index ?? "") === "") ? url : [url],
success: () => { success: () => {
// 预览成功后,延迟重置标志位(给用户时间关闭预览) // 预览成功后,延迟重置标志位(给用户时间关闭预览)
setTimeout(() => { setTimeout(() => {
...@@ -693,11 +693,11 @@ Page({ ...@@ -693,11 +693,11 @@ Page({
}); });
}, },
// 分割媒体URL(处理逗号分隔的多个URL) // 分割媒体URL(多个URL用逗号连接,但OSS参数内也有逗号,只在逗号后紧跟http时拆分)
splitMediaUrls(urlString) { splitMediaUrls(urlString) {
if (!urlString) return []; if (!urlString) return [];
if (typeof urlString !== "string") return [urlString]; if (typeof urlString !== "string") return [urlString];
return urlString.split(",").filter((url) => url.trim()); return urlString.split(/,(?=https?:\/\/)/).filter((url) => url.trim());
}, },
// PDF/HTML预览 // PDF/HTML预览
...@@ -1046,7 +1046,12 @@ Page({ ...@@ -1046,7 +1046,12 @@ Page({
tabs.find((i) => i.key === "payment").hidden = false; tabs.find((i) => i.key === "payment").hidden = false;
} }
if (detailsInfo.signingInfo.saleContract) { if (detailsInfo.signingInfo.saleContract) {
detailsInfo.signingInfo.saleContract.signerTypeStr = detailsInfo.signingInfo.saleContract.signerType == 0 ? '个人' : detailsInfo.signingInfo.saleContract.signerType == 1 ? '企业委托' : '企业' detailsInfo.signingInfo.saleContract.signerTypeStr =
detailsInfo.signingInfo.saleContract.signerType == 0
? "个人"
: detailsInfo.signingInfo.saleContract.signerType == 1
? "企业委托"
: "企业";
// 判断签约信息 // 判断签约信息
tabs.find((i) => i.key === "contract").hidden = false; tabs.find((i) => i.key === "contract").hidden = false;
} }
...@@ -1181,6 +1186,13 @@ Page({ ...@@ -1181,6 +1186,13 @@ Page({
}); });
}, },
handleError(e) {
console.log(e, "e---------handleError");
},
handleLoad(e) {
console.log(e, "e---------handleLoad");
},
/** /**
* 生命周期函数--监听页面加载 * 生命周期函数--监听页面加载
*/ */
......
...@@ -128,19 +128,38 @@ ...@@ -128,19 +128,38 @@
return value; return value;
}; };
// 分割媒体URL(处理逗号分隔的多个URL) // 分割媒体URL(多个URL用逗号连接,但OSS参数内也有逗号,只在逗号后紧跟http时拆分)
var splitMediaUrls = function(urlString) { var splitMediaUrls = function(urlString) {
if (!urlString) return []; if (!urlString) return [];
if (typeof urlString !== 'string') return [urlString]; if (typeof urlString !== 'string') return [urlString];
var urls = urlString.split(',');
var result = []; var result = [];
for (var i = 0; i < urls.length; i++) { var sep1 = ',https://';
var url = urls[i].trim(); var sep2 = ',http://';
if (url) { var remaining = urlString.trim();
result.push(url); while (remaining) {
var idx1 = remaining.indexOf(sep1);
var idx2 = remaining.indexOf(sep2);
var idx = -1;
var nextUrl = '';
if (idx1 >= 0 && idx2 >= 0) {
idx = idx1 < idx2 ? idx1 : idx2;
nextUrl = idx1 < idx2 ? 'https://' : 'http://';
} else if (idx1 >= 0) {
idx = idx1;
nextUrl = 'https://';
} else if (idx2 >= 0) {
idx = idx2;
nextUrl = 'http://';
}
if (idx >= 0) {
result.push(remaining.substring(0, idx).trim());
remaining = nextUrl + remaining.substring(idx + nextUrl.length);
} else {
result.push(remaining.trim());
break;
} }
} }
return result; return result.filter(function(u) { return u; });
}; };
// 判断字符串是否包含指定子串 // 判断字符串是否包含指定子串
...@@ -149,6 +168,18 @@ ...@@ -149,6 +168,18 @@
return str.indexOf(searchStr) !== -1; return str.indexOf(searchStr) !== -1;
}; };
// 获取视频封面图 URL:优先 coverUrl,其次 OSS 视频用 snapshot 生成,否则用默认图
var getVideoCoverUrl = function(videoUrl, coverUrl, defaultImg) {
if (coverUrl && coverUrl !== '' && coverUrl.indexOf('.mp4') === -1 && coverUrl.indexOf('.mov') === -1 && coverUrl.indexOf('.avi') === -1) {
return coverUrl;
}
if (videoUrl && videoUrl.indexOf('aliyuncs.com') !== -1) {
var sep = videoUrl.indexOf('?') >= 0 ? '&' : '?';
return videoUrl + sep + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast';
}
return defaultImg || '';
};
// 判断URL是否是视频格式(支持多种视频格式) // 判断URL是否是视频格式(支持多种视频格式)
var isVideoUrl = function(url) { var isVideoUrl = function(url) {
if (!url || typeof url !== 'string') return false; if (!url || typeof url !== 'string') return false;
...@@ -259,6 +290,7 @@ ...@@ -259,6 +290,7 @@
return ''; return '';
}; };
module.exports = { module.exports = {
getValueByPath: getValueByPath, getValueByPath: getValueByPath,
formatValue: formatValue, formatValue: formatValue,
...@@ -270,7 +302,8 @@ ...@@ -270,7 +302,8 @@
shouldShowItem: shouldShowItem, shouldShowItem: shouldShowItem,
shouldShowContractItem: shouldShowContractItem, shouldShowContractItem: shouldShowContractItem,
isVideoUrl: isVideoUrl, isVideoUrl: isVideoUrl,
getTabName: getTabName getTabName: getTabName,
getVideoCoverUrl: getVideoCoverUrl
}; };
</wxs> </wxs>
<view class="evaluationFormDetails"> <view class="evaluationFormDetails">
...@@ -430,7 +463,7 @@ ...@@ -430,7 +463,7 @@
<view class="upload-label">{{ field.label }}</view> <view class="upload-label">{{ field.label }}</view>
<view class="upload-images-wrapper"> <view class="upload-images-wrapper">
<view class="uploaded-media-container"> <view class="uploaded-media-container">
<image src="{{imageDataMap[field.key].fileUrl}}" mode="aspectFill" class="uploaded-media" catchtap="previewMedia" data-url="{{imageDataMap[field.key].fileUrl}}" data-type="1" /> <image src="{{imageDataMap[field.key].fileUrl}}" mode="aspectFill" class="uploaded-media" catchtap="previewMedia" data-url="{{imageDataMap[field.key].fileUrl}}" data-type="1" binderror="handleError" />
</view> </view>
</view> </view>
</view> </view>
...@@ -474,7 +507,7 @@ ...@@ -474,7 +507,7 @@
<view class="upload-images-wrapper"> <view class="upload-images-wrapper">
<view class="uploaded-media-container" catchtap="previewMedia" data-url="{{imageDataMap[field.key].fileUrl}}" data-type="2"> <view class="uploaded-media-container" catchtap="previewMedia" data-url="{{imageDataMap[field.key].fileUrl}}" data-type="2">
<view class="video-container"> <view class="video-container">
<image src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFill" class="uploaded-media" /> <image src="{{ utils.getVideoCoverUrl(imageDataMap[field.key].fileUrl, imageDataMap[field.key].coverUrl, IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFill" class="uploaded-media" />
<view class="video-play-icon"> <view class="video-play-icon">
<view class="sprite-icon icon-upload-play"></view> <view class="sprite-icon icon-upload-play"></view>
</view> </view>
...@@ -581,7 +614,7 @@ ...@@ -581,7 +614,7 @@
<!-- 单字段多图片 --> <!-- 单字段多图片 -->
<view wx:elif="{{item.type == 'imageArr'}}" class="flex flex-wrap"> <view wx:elif="{{item.type == 'imageArr'}}" class="flex flex-wrap">
<block wx:for="{{utils.getValueByPath(detailsInfo, item.key, true)}}" wx:for-item="subItem" wx:for-index="subIndex" wx:key="subIndex"> <block wx:for="{{utils.getValueByPath(detailsInfo, item.key, true)}}" wx:for-item="subItem" wx:for-index="subIndex" wx:key="subIndex">
<image wx:if="{{subItem}}" src="{{subItem}}" mode="aspectFill" class="cert-image mr-16" catchtap="previewMedia" data-url="{{ utils.getValueByPath(detailsInfo, item.key, true)}}" data-index="{{subIndex}}" data-type="1"/> <image wx:if="{{subItem}}" src="{{subItem}}" mode="aspectFill" class="cert-image mr-16" catchtap="previewMedia" data-url="{{ utils.getValueByPath(detailsInfo, item.key, true)}}" data-index="{{subIndex}}" data-type="1" />
</block> </block>
</view> </view>
<!-- 单张图片或视频(根据文件类型判断) --> <!-- 单张图片或视频(根据文件类型判断) -->
...@@ -589,7 +622,7 @@ ...@@ -589,7 +622,7 @@
<!-- 判断是否是视频 --> <!-- 判断是否是视频 -->
<block wx:if="{{utils.isVideoUrl(utils.getValueByPath(detailsInfo, item.key))}}"> <block wx:if="{{utils.isVideoUrl(utils.getValueByPath(detailsInfo, item.key))}}">
<view class="cert-image video-container" catchtap="previewMedia" data-url="{{ utils.getValueByPath(detailsInfo, item.key) }}" data-type="2"> <view class="cert-image video-container" catchtap="previewMedia" data-url="{{ utils.getValueByPath(detailsInfo, item.key) }}" data-type="2">
<image src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFill" class="cert-image" /> <image src="{{ utils.getVideoCoverUrl(utils.getValueByPath(detailsInfo, item.key), '', IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFill" class="cert-image" />
<view class="video-play-icon"> <view class="video-play-icon">
<view class="sprite-icon icon-upload-play"></view> <view class="sprite-icon icon-upload-play"></view>
</view> </view>
...@@ -629,7 +662,7 @@ ...@@ -629,7 +662,7 @@
<!-- 判断是否是视频 --> <!-- 判断是否是视频 -->
<block wx:if="{{utils.isVideoUrl(utils.getValueByPath(detailsInfo, item.key))}}"> <block wx:if="{{utils.isVideoUrl(utils.getValueByPath(detailsInfo, item.key))}}">
<view class="cert-image video-container" catchtap="previewMedia" data-url="{{ utils.getValueByPath(detailsInfo, item.key) }}" data-type="2"> <view class="cert-image video-container" catchtap="previewMedia" data-url="{{ utils.getValueByPath(detailsInfo, item.key) }}" data-type="2">
<image src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFill" class="cert-image" /> <image src="{{ utils.getVideoCoverUrl(utils.getValueByPath(detailsInfo, item.key), '', IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFill" class="cert-image" />
<view class="video-play-icon"> <view class="video-play-icon">
<view class="sprite-icon icon-upload-play"></view> <view class="sprite-icon icon-upload-play"></view>
</view> </view>
...@@ -692,14 +725,14 @@ ...@@ -692,14 +725,14 @@
<block wx:if="{{item.key === 'carHandoverInfo.handoverPhotoMore'}}"> <block wx:if="{{item.key === 'carHandoverInfo.handoverPhotoMore'}}">
<block wx:for="{{utils.splitMediaUrls(utils.getValueByPath(detailsInfo, item.key))}}" wx:key="urlIdx" wx:for-item="url" wx:for-index="urlIdx"> <block wx:for="{{utils.splitMediaUrls(utils.getValueByPath(detailsInfo, item.key))}}" wx:key="urlIdx" wx:for-item="url" wx:for-index="urlIdx">
<view class="uploaded-media-container"> <view class="uploaded-media-container">
<image src="{{url}}" mode="aspectFill" class="uploaded-media" catchtap="previewMedia" data-url="{{url}}" data-type="1" /> <image src="{{url}}" mode="aspectFill" class="uploaded-media" catchtap="previewMedia" data-url="{{url}}" data-type="1" binderror="handleError" bindload="handleLoad" />
</view> </view>
</block> </block>
</block> </block>
<!-- 其他单张图片 --> <!-- 其他单张图片 -->
<block wx:else> <block wx:else>
<view class="uploaded-media-container"> <view class="uploaded-media-container">
<image src="{{utils.getValueByPath(detailsInfo, item.key)}}" mode="aspectFill" class="uploaded-media" catchtap="previewMedia" data-url="{{utils.getValueByPath(detailsInfo, item.key)}}" data-type="1" /> <image src="{{utils.getValueByPath(detailsInfo, item.key)}}" mode="aspectFill" class="uploaded-media" catchtap="previewMedia" data-url="{{utils.getValueByPath(detailsInfo, item.key)}}" data-type="1" binderror="handleError" bindload="handleLoad" />
</view> </view>
</block> </block>
</view> </view>
...@@ -731,7 +764,7 @@ ...@@ -731,7 +764,7 @@
<block wx:if="{{utils.isVideoUrl(utils.getValueByPath(detailsInfo, item.key))}}"> <block wx:if="{{utils.isVideoUrl(utils.getValueByPath(detailsInfo, item.key))}}">
<view class="uploaded-media-container"> <view class="uploaded-media-container">
<view class="video-container" catchtap="previewMedia" data-url="{{utils.getValueByPath(detailsInfo, item.key)}}" data-type="2"> <view class="video-container" catchtap="previewMedia" data-url="{{utils.getValueByPath(detailsInfo, item.key)}}" data-type="2">
<image src="{{ IMG_URL }}usedCar/video_default.png" mode="aspectFill" class="uploaded-media" /> <image src="{{ utils.getVideoCoverUrl(utils.getValueByPath(detailsInfo, item.key), '', IMG_URL + 'usedCar/video_default.png') }}" mode="aspectFill" class="uploaded-media" />
<view class="video-play-icon"> <view class="video-play-icon">
<view class="sprite-icon icon-upload-play"></view> <view class="sprite-icon icon-upload-play"></view>
</view> </view>
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
const IMG_URL = "https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/" const IMG_URL = "https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/"
import dayjs from 'dayjs' import dayjs from 'dayjs'
import api from '~/api/api.js' import api from '~/api/api.js'
import { uploadFile } from '~/utils/oss/ossUpload.js'
import newApi from '~/packageUsedCar/api' import newApi from '~/packageUsedCar/api'
import mapApi from "~/utils/mapapi/mapapi"; import mapApi from "~/utils/mapapi/mapapi";
Page({ Page({
...@@ -762,34 +763,21 @@ Page({ ...@@ -762,34 +763,21 @@ Page({
wx.$util.showLoading('上传中') wx.$util.showLoading('上传中')
try { try {
for (const item of tempFiles) { for (const item of tempFiles) {
const val = item.path const fileObj = {
const imgType = val.split('.')[1] tempFilePath: item.path || item.tempFilePath,
const type = imgType === 'unknown' ? 'jpg' : imgType url: item.path || item.tempFilePath,
const _res = await new Promise((resolve, reject) => { size: item.size,
wx.getFileSystemManager().readFile({ }
filePath: val, // 选择图片返回的相对路径 const data = await uploadFile(fileObj)
encoding: 'base64', // 编码格式 _this.setData({
success: resolve, [`formData.${field}`]: data
fail: reject
})
})
const img = await api.uploadImg({
file: `${type}@${_res.data}`
}) })
const { code, data, message } = img if (field == 'orgLicenseUrl') {
if (code == 0) { orgLicenseImages?.push(data)
_this.setData({ _this.setData({
[`formData.${field}`]: data orgLicenseImages,
[`formData.${field}`]: orgLicenseImages?.join(',')
}) })
if (field == 'orgLicenseUrl') {
orgLicenseImages?.push(data)
_this.setData({
orgLicenseImages,
[`formData.${field}`]: orgLicenseImages?.join(',')
})
}
} else {
wx.$util.showToast(message)
} }
} }
} catch (error) { } catch (error) {
...@@ -819,30 +807,18 @@ Page({ ...@@ -819,30 +807,18 @@ Page({
wx.$util.showLoading('上传中') wx.$util.showLoading('上传中')
try { try {
for (const item of tempFiles) { for (const item of tempFiles) {
const val = item.tempFilePath const fileObj = {
const imgType = val.split('.')[1] tempFilePath: item.tempFilePath || item.path,
const type = imgType === 'unknown' ? 'mp4' : imgType url: item.tempFilePath || item.path,
const _res = await new Promise((resolve, reject) => { size: item.size,
wx.getFileSystemManager().readFile({
filePath: val, // 选择图片返回的相对路径
encoding: 'base64', // 编码格式
success: resolve,
fail: reject
})
})
const img = await api.uploadFileWithCover({
file: `${type}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
_this.setData({
'formData.thirdPartyTransactionVoucher': data.videoUrl,
thirdPartyTransactionType: 'video',
thirdPartyTransactionCoverUrl: data?.coverUrl
})
} else {
wx.$util.showToast(message)
} }
const videoUrl = await uploadFile(fileObj)
const coverUrl = videoUrl + (videoUrl.indexOf('?') >= 0 ? '&' : '?') + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
_this.setData({
'formData.thirdPartyTransactionVoucher': videoUrl,
thirdPartyTransactionType: 'video',
thirdPartyTransactionCoverUrl: coverUrl
})
} }
} catch (error) { } catch (error) {
wx.$util.showToast("上传失败,请重试") wx.$util.showToast("上传失败,请重试")
...@@ -891,45 +867,31 @@ Page({ ...@@ -891,45 +867,31 @@ Page({
wx.$util.showLoading('上传中') wx.$util.showLoading('上传中')
try { try {
for (const item of tempFiles) { for (const item of tempFiles) {
const val = item.tempFilePath const fileObj = {
const imgType = val.split('.')[1] tempFilePath: item.tempFilePath || item.path,
const type = imgType === 'unknown' ? 'jpg' : imgType url: item.tempFilePath || item.path,
const _res = await new Promise((resolve, reject) => { size: item.size,
wx.getFileSystemManager().readFile({ }
filePath: val, // 选择图片返回的相对路径 const url = await uploadFile(fileObj)
encoding: 'base64', // 编码格式 if (fileType == 'video') {
success: resolve, const coverUrl = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
fail: reject _this.setData({
['formData.thirdPartyTransactionType']: 'video',
[`formData.${field}`]: url,
thirdPartyTransactionType: res.type,
thirdPartyTransactionCoverUrl: coverUrl
}) })
}) } else {
const img = await api[requestEvent]({
file: `${type}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
if (fileType == 'video') {
_this.setData({
['formData.thirdPartyTransactionType']: 'video',
})
}
_this.setData({ _this.setData({
[`formData.${field}`]: fileType == 'video' ? data.videoUrl : data, [`formData.${field}`]: url,
}) })
if (field == 'thirdPartyTransactionVoucher') {
_this.setData({
thirdPartyTransactionType: res.type,
thirdPartyTransactionCoverUrl: data?.coverUrl
})
}
if (field == 'orgLicenseUrl') { if (field == 'orgLicenseUrl') {
orgLicenseImages?.push(data) orgLicenseImages?.push(url)
_this.setData({ _this.setData({
orgLicenseImages, orgLicenseImages,
[`formData.${field}`]: orgLicenseImages?.join(',') [`formData.${field}`]: orgLicenseImages?.join(',')
}) })
} }
} else {
wx.$util.showToast(message)
} }
} }
} catch (error) { } catch (error) {
......
{ {
"projectname": "%E7%B2%BE%E5%93%81%E5%8D%87%E7%BA%A7", "projectname": "%E7%B2%BE%E5%93%81%E5%8D%87%E7%BA%A7",
"compileType": "miniprogram", "compileType": "miniprogram",
"libVersion": "3.13.1", "libVersion": "3.13.1",
"packOptions": { "packOptions": {
"ignore": [ "ignore": [
{ {
"value": ".vscode", "value": ".vscode",
"type": "folder" "type": "folder"
} }
], ],
"include": [] "include": []
}, },
"setting": { "setting": {
"urlCheck": false, "urlCheck": false,
"coverView": true, "coverView": true,
"es6": true, "es6": true,
"postcss": true, "postcss": true,
"minified": true, "minified": true,
"enhance": true, "enhance": true,
"showShadowRootInWxmlPanel": true, "showShadowRootInWxmlPanel": true,
"packNpmRelationList": [], "packNpmRelationList": [],
"ignoreUploadUnusedFiles": true, "ignoreUploadUnusedFiles": true,
"babelSetting": { "babelSetting": {
"ignore": [], "ignore": [],
"disablePlugins": [], "disablePlugins": [],
"outputPath": "" "outputPath": ""
}, },
"useCompilerPlugins": [ "useCompilerPlugins": [
"sass" "sass"
], ],
"ignoreDevUnusedFiles": false, "ignoreDevUnusedFiles": false,
"minifyWXML": true, "minifyWXML": true,
"compileWorklet": false, "compileWorklet": false,
"uglifyFileName": false, "uglifyFileName": false,
"uploadWithSourceMap": true, "uploadWithSourceMap": true,
"packNpmManually": false, "packNpmManually": false,
"minifyWXSS": true, "minifyWXSS": true,
"localPlugins": false, "localPlugins": false,
"disableUseStrict": false, "disableUseStrict": false,
"condition": false, "condition": false,
"swc": false, "swc": false,
"disableSWC": true "disableSWC": true
}, },
"editorSetting": { "editorSetting": {
"tabIndent": "insertSpaces", "tabIndent": "insertSpaces",
"tabSize": 2 "tabSize": 2
}, },
"appid": "wx570d9331f9ace0bd", "appid": "wx570d9331f9ace0bd",
"simulatorPluginLibVersion": {} "simulatorPluginLibVersion": {}
} }
\ No newline at end of file \ No newline at end of file
{ {
"libVersion": "3.13.1", "libVersion": "3.13.1",
"projectname": "dj-car-boutique-work-wechat", "projectname": "dj-car-boutique-work-wechat",
"setting": { "setting": {
"urlCheck": false, "urlCheck": false,
"coverView": true, "coverView": true,
"showShadowRootInWxmlPanel": true, "showShadowRootInWxmlPanel": true,
"ignoreDevUnusedFiles": false, "ignoreDevUnusedFiles": false,
"lazyloadPlaceholderEnable": false, "lazyloadPlaceholderEnable": false,
"skylineRenderEnable": false, "skylineRenderEnable": false,
"preloadBackgroundData": false, "preloadBackgroundData": false,
"autoAudits": false, "autoAudits": false,
"compileHotReLoad": true, "compileHotReLoad": true,
"useApiHook": true, "useApiHook": true,
"useStaticServer": false, "useStaticServer": false,
"useLanDebug": false, "useLanDebug": false,
"showES6CompileOption": false, "showES6CompileOption": false,
"checkInvalidKey": true, "checkInvalidKey": true,
"bigPackageSizeSupport": true "bigPackageSizeSupport": true,
} "useApiHostProcess": true
}
} }
\ No newline at end of file \ No newline at end of file
import config from '@/config.js'
// 在h5端上传涉及到跨域,需在阿里云上配置跨域规则才能正常使用
module.exports = {
bucketName: config.BUKET_NAME,
folder: config.FOLDER,
uploadUrl: config.OSS_DOMAIN + '/', // 默认存在根目录后面要跟个'/' (在你当前小程序的后台的uploadFile 合法域名也要配上这个域名)
AccessKeySecret: config.ACCESSKEYSECRET, // AccessKeySecret 去你的阿里云上控制台上找
OSSAccessKeyId: config.ACCESSKEYID, // AccessKeyId 去你的阿里云上控制台上找
timeout: 87600 // 这个是上传文件时Policy的失效时间
}
This diff could not be displayed because it is too large.
import Crypto from './crypto.js'
(function() {
// Shortcut
var util = Crypto.util;
Crypto.HMAC = function(hasher, message, key, options) {
// Allow arbitrary length keys
key = key.length > hasher._blocksize * 4 ?
hasher(key, {
asBytes: true
}) :
util.stringToBytes(key);
// XOR keys with pad constants
var okey = key,
ikey = key.slice(0);
for (var i = 0; i < hasher._blocksize * 4; i++) {
okey[i] ^= 0x5C;
ikey[i] ^= 0x36;
}
var hmacbytes = hasher(util.bytesToString(okey) +
hasher(util.bytesToString(ikey) + message, {
asString: true
}), {
asBytes: true
});
return options && options.asBytes ? hmacbytes :
options && options.asString ? util.bytesToString(hmacbytes) :
util.bytesToHex(hmacbytes);
};
})();
module.exports = Crypto;
import api from "~/api/api.js";
import base64 from "./base64.js";
import Crypto from "./crypto.js";
const baseConfig = {
// 阿里云oss域名 格式:https://xxx.oss-cn-xxx.aliyuncs.com
OSS_DOMAIN: "https://glsk-oss.oss-cn-shenzhen.aliyuncs.com",
// 文件直传到阿里云oss时需用到
ACCESSKEYID: "LTAI5tCRcCUgd7bt1J7JY596",
ACCESSKEYSECRET: "kJos9mgylkR5ztosnDt8Asrc3ulgqy",
BUKET_NAME: "glsk-oss",
FOLDER: "usedCar/",
// 与后端约定的token字段名
TOKEN_NAME: "glsk-oss",
// PROTOCAL: 'http',
// SERVER: 'app-admin-server.test.glsx.com.cn',
// SOCKET_PORT: '9081',
// HTTP_PORT: '3000',
HTTP_SERVER: "http://app-admin-server.glsx.com.cn",
SOCKET_SERVER: "http://app-admin-server.glsx.com.cn",
FILE_UPLOAD_URL: "file/upload",
};
const config = {
bucketName: baseConfig.BUKET_NAME,
folder: baseConfig.FOLDER,
uploadUrl: baseConfig.OSS_DOMAIN + "/", // 默认存在根目录后面要跟个'/' (在你当前小程序的后台的uploadFile 合法域名也要配上这个域名)
AccessKeySecret: baseConfig.ACCESSKEYSECRET, // AccessKeySecret 去你的阿里云上控制台上找
OSSAccessKeyId: baseConfig.ACCESSKEYID, // AccessKeyId 去你的阿里云上控制台上找
timeout: 87600, // 这个是上传文件时Policy的失效时间
};
/**
* 上传文件到阿里云oss
* @param {Object} file 文件信息,支持格式:{ fileType, size, tempFilePath, thumb, type, url }
* - tempFilePath / url: 本地临时路径,用于上传
* - size: 文件大小(字节)
* - fileType / type: 文件类型,如 "image"
* @return 完整的图片/文件地址
*/
const uploadFile = async function (file) {
const res = await api.getSceneMarketConfig();
console.log(res, "res");
// const { data } = await api.fetchApiConfig(config.bucketName);
// console.log(data, "data");
// return;
// 兼容只传 file 对象:从 tempFilePath 或 url 取上传路径
const filePath = file.tempFilePath || file.url;
if (!filePath) {
return Promise.reject(
new Error("缺少文件路径:请提供 tempFilePath 或 url")
);
}
console.log("上传文件到阿里云oss", file);
return new Promise(async (resolve, reject) => {
// 从路径中提取文件后缀(支持 http://tmp/xxx.jpg 或 本地路径)
const getExtension = (path) => {
if (!path) return "";
const name = path.split("/").pop() || path;
const lastDot = name.lastIndexOf(".");
return lastDot > -1 ? name.slice(lastDot + 1).toLowerCase() : "";
};
const fileExtension = getExtension(filePath);
// 添加文件大小限制检查
if (file.size) {
const imageTypes = ["jpg", "jpeg", "png", "gif", "bmp"];
const videoTypes = ["mp4", "avi", "mov", "wmv", "flv", "mkv"];
const fileSizeMB = file.size / (1024 * 1024);
if (imageTypes.includes(fileExtension) && fileSizeMB > 10) {
// uni.showToast({ title: "图片上传最大10MB", icon: "none" });
reject(new Error("图片上传最大10MB"));
return;
}
if (videoTypes.includes(fileExtension) && fileSizeMB > 100) {
// uni.showToast({ title: "视频上传最大100MB", icon: "none" });
reject(new Error("视频上传最大100MB"));
return;
}
}
const timestamp = Date.now();
const randomStr = Math.random().toString(36).substring(2, 10);
const randomNum = timestamp + "_" + randomStr;
const ext = fileExtension || "jpg"; // 无后缀时默认 jpg(常见于选图)
let aliyunFileKey = config.folder + randomNum + "." + ext;
console.log(aliyunFileKey, "aliyunFileKey");
const aliyunServerURL = config.uploadUrl;
// 4. 生成 policy,并根据 policy 计算签名
const { lsaccessKeySecret, securityToken, lsaccessKeyId } =
await getOssToken();
const { policy, signature } = getPolicyBase64(
aliyunFileKey,
lsaccessKeySecret
);
console.log(signature, "signaturesignaturesignature");
// 5. 组装 x-oss-credential,AccessKeyId 使用 STS 返回的临时 key(lsaccessKeyId)
const accessKeyId = lsaccessKeyId || config.OSSAccessKeyId;
const formData = {
key: aliyunFileKey,
OSSAccessKeyId: accessKeyId,
policy: policy,
signature: signature,
success_action_status: "200",
"x-oss-security-token": securityToken,
};
console.log(formData, "formData");
wx.uploadFile({
url: aliyunServerURL,
filePath: filePath,
name: "file",
formData: formData,
success: function (res) {
console.log(res, 444);
if (res.statusCode != 200) {
reject();
} else {
// 上传成功后删除临时文件(uni.removeSavedFile 需传 filePath)
wx.getFileSystemManager().removeSavedFile({
filePath: filePath,
success: function (res) {
console.log(res);
},
});
}
const rawUrl = aliyunServerURL + aliyunFileKey;
const videoTypes = ["mp4", "avi", "mov", "wmv", "flv", "mkv"];
const isVideo = videoTypes.includes(fileExtension);
// 仅对图片追加处理参数,视频返回直链
const finalUrl = isVideo
? rawUrl
: rawUrl + (rawUrl.indexOf("?") >= 0 ? "&" : "?") + "x-oss-process=image/format,jpg/quality,q_100";
resolve(finalUrl);
},
fail: function (err) {
console.log(err, 555);
err.domainName = aliyunServerURL;
reject(err);
},
});
});
};
const getPolicyBase64 = function (aliyunFileKey, accessKeySecret) {
// 生成过期时间(1小时后)
const expiration = new Date(Date.now() + 3600 * 1000).toISOString();
// 构造 policy(定义上传规则)
const policyObj = {
expiration: expiration,
conditions: [
{ bucket: config.bucket },
["eq", "$key", aliyunFileKey],
["content-length-range", 0, 1048576000], // 最大 1GB
],
};
// Base64 编码 policy
const policyBase64 = base64.encode(JSON.stringify(policyObj));
console.log(accessKeySecret, "policyBase64");
// HMAC-SHA1 签名(使用 AccessKeySecret)
const bytes = Crypto.HmacSHA1(policyBase64, accessKeySecret);
const signature = Crypto.enc.Base64.stringify(bytes);
return {
policy: policyBase64,
signature: signature,
};
};
const getOssToken = async function () {
console.log("getOssToken");
const res = await api.getToken({});
// 根据通用 request 封装,这里的 res 就是 response.data,
// 真实业务数据在 res.data 里
const tokenData = res && res.data ? res.data : res || {};
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = tokenData;
if (!lsaccessKeySecret) {
console.error("获取 OSS Token 失败,lsaccessKeySecret 为空:", res);
throw new Error("获取 OSS Token 失败");
}
return {
lsaccessKeySecret,
securityToken,
lsaccessKeyId,
};
};
module.exports = { uploadFile };
import Crypto from './crypto.js'
(function() {
// Shortcut
var util = Crypto.util;
// Public API
var SHA1 = Crypto.SHA1 = function(message, options) {
var digestbytes = util.wordsToBytes(SHA1._sha1(message));
return options && options.asBytes ? digestbytes :
options && options.asString ? util.bytesToString(digestbytes) :
util.bytesToHex(digestbytes);
};
// The core
SHA1._sha1 = function(message) {
var m = util.stringToWords(message),
l = message.length * 8,
w = [],
H0 = 1732584193,
H1 = -271733879,
H2 = -1732584194,
H3 = 271733878,
H4 = -1009589776;
// Padding
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >>> 9) << 4) + 15] = l;
for (var i = 0; i < m.length; i += 16) {
var a = H0,
b = H1,
c = H2,
d = H3,
e = H4;
for (var j = 0; j < 80; j++) {
if (j < 16) w[j] = m[i + j];
else {
var n = w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16];
w[j] = (n << 1) | (n >>> 31);
}
var t = ((H0 << 5) | (H0 >>> 27)) + H4 + (w[j] >>> 0) + (
j < 20 ? (H1 & H2 | ~H1 & H3) + 1518500249 :
j < 40 ? (H1 ^ H2 ^ H3) + 1859775393 :
j < 60 ? (H1 & H2 | H1 & H3 | H2 & H3) - 1894007588 :
(H1 ^ H2 ^ H3) - 899497514);
H4 = H3;
H3 = H2;
H2 = (H1 << 30) | (H1 >>> 2);
H1 = H0;
H0 = t;
}
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += e;
}
return [H0, H1, H2, H3, H4];
};
// Package private blocksize
SHA1._blocksize = 16;
})();
module.exports = Crypto;
import { secretKey, domain, path, sign } from "./http.js"; import { secretKey, domain, path, sign } from "./http.js";
// console.log(secretKey, 'secretKey') // console.log(secretKey, 'secretKey')
import util from "~/utils/util.js"; import util from "~/utils/util.js";
import { envIndex } from "~/config"; import { envIndex } from "~/config";
import qs from "~/utils/lib/qs"; import qs from "~/utils/lib/qs";
/**接口 */ /**接口 */
class Request { class Request {
get(method, data, noSignAttr, requestPath, domainName, failTips) { get(method, data, noSignAttr, requestPath, domainName, failTips) {
return this.request("GET", method, data, noSignAttr, requestPath, domainName, failTips); return this.request("GET", method, data, noSignAttr, requestPath, domainName, failTips);
} }
post(method, data, noSignAttr, requestPath, domainName, failTips) { post(method, data, noSignAttr, requestPath, domainName, failTips) {
return this.request("POST", method, data, noSignAttr, requestPath, domainName, failTips); return this.request("POST", method, data, noSignAttr, requestPath, domainName, failTips);
} }
request(RequestMethods, method, data, noSignAttr = [], requestPath, domainName = "dj", failTips = true) { request(RequestMethods, method, data, noSignAttr = [], requestPath, domainName = "dj", failTips = true) {
let _this = this; let _this = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
wx.showNavigationBarLoading(); wx.showNavigationBarLoading();
wx.getNetworkType({ wx.getNetworkType({
success(res) { success(res) {
if (res.networkType == "none") { if (res.networkType == "none") {
wx.hideLoading(); wx.hideLoading();
wx.showToast({ wx.showToast({
title: "网络异常", title: "网络异常",
icon: "none", icon: "none",
}); });
return; return;
} }
if (!data) data = {}; if (!data) data = {};
let header = let header =
RequestMethods === "POST" RequestMethods === "POST"
? { ? {
"content-type": "application/x-www-form-urlencoded", "content-type": "application/x-www-form-urlencoded",
} }
: {}; : {};
let url = `${domain[domainName]}${requestPath || path}`; let url = `${domain[domainName]}${requestPath || path}`;
// console.log(requestPath) // console.log(requestPath)
if (method) { if (method) {
data = _this.getData(data, method, noSignAttr, domainName == "merchants"); data = _this.getData(data, method, noSignAttr, domainName == "merchants");
url = `${domain[domainName]}${requestPath || path}?method=${method}`; url = `${domain[domainName]}${requestPath || path}?method=${method}`;
} else { } else {
header = { header = {
"content-type": "application/json", "content-type": "application/json",
}; };
} }
// console.log('reqData',data?.sessionId); // console.log('reqData',data?.sessionId);
// delete // delete
// if (data?.sessionId) { // if (data?.sessionId) {
// delete data?.sessionId // delete data?.sessionId
// } // }
wx.request({ wx.request({
url, url,
data, data,
method: RequestMethods, method: RequestMethods,
header, header,
dataType: "json", dataType: "json",
responseType: "text", responseType: "text",
timeout: noSignAttr?.includes("file") ? 120 * 1000 : 60 * 1000, timeout: noSignAttr?.includes("file") ? 120 * 1000 : 60 * 1000,
success(response) { success(response) {
/**业务代码 */ /**业务代码 */
let { let {
data: { code, message, subErrors }, data: { code, message, subErrors },
data, data,
} = response; } = response;
if (code == 20 || code == 21) { if (code == 20 || code == 21) {
let thisPage = wx.$router.getPageInstance(); let thisPage = wx.$router.getPageInstance();
// console.log(thisPage); // console.log(thisPage);
wx.hideLoading(); wx.hideLoading();
if (thisPage.route != "pages/wxLogin/wxLogin") { if (thisPage.route != "pages/wxLogin/wxLogin") {
getApp().login(true, "", url); getApp().login(true, "", url);
} }
} else if (code == -1) { } else if (code == -1) {
wx.showToast({ wx.showToast({
title: message || "网络请求失败", title: message || "网络请求失败",
icon: "none", icon: "none",
}); });
resolve(data); resolve(data);
} else { } else {
// util.debounce( getApp().test(true),500) // util.debounce( getApp().test(true),500)
// getApp().test() // getApp().test()
// console.log(data,'data'); // console.log(data,'data');
resolve(data); resolve(data);
} }
}, },
fail(error) { fail(error) {
wx.hideLoading(); wx.hideLoading();
console.error(`接口异常:${domain[domainName]}${requestPath || path}?method=${method}`, error); console.error(`接口异常:${domain[domainName]}${requestPath || path}?method=${method}`, error);
if (failTips) { if (failTips) {
wx.showToast({ wx.showToast({
title: "系统异常", title: "系统异常",
icon: "error", icon: "error",
}); });
} }
reject(error); reject(error);
}, },
complete() { complete() {
wx.stopPullDownRefresh(); wx.stopPullDownRefresh();
wx.hideNavigationBarLoading(); wx.hideNavigationBarLoading();
}, },
}); });
}, },
}); });
}); });
} }
getData(data, method, noSignAttr, merchant) { getData(data, method, noSignAttr, merchant) {
let sessionId = util.getSessionId(); let sessionId = util.getSessionId();
if (sessionId) data["sessionId"] = sessionId; if (sessionId) data["sessionId"] = sessionId;
// console.log(data,'request'); // console.log(data,'request');
data["v"] = "1.0.0"; data["v"] = "1.0.0";
data["method"] = method; data["method"] = method;
data["format"] = "json"; data["format"] = "json";
data["locale"] = "zh_CN"; data["locale"] = "zh_CN";
data["source"] = "dj-wechat"; data["source"] = "dj-wechat";
// 兼容线上dj和scrm appkey和secret不一样的情况 // 兼容线上dj和scrm appkey和secret不一样的情况
let apiName = data.method.split(".api")[0]; let apiName = data.method.split(".api")[0];
// 为空报错 // 为空报错
if (!apiName) { if (!apiName) {
throw new Error("apiName is null"); throw new Error("apiName is null");
} }
if (apiName.split(".").length > 1) apiName = apiName.split(".")[0]; if (apiName.split(".").length > 1) apiName = apiName.split(".")[0];
if (merchant) apiName = "merchants"; if (merchant) apiName = "merchants";
const appKey = secretKey[apiName].appKey; const appKey = secretKey[apiName].appKey;
const secret = secretKey[apiName].secret; const secret = secretKey[apiName].secret;
data["appKey"] = appKey; data["appKey"] = appKey;
let obj = sign(data, secret, noSignAttr); let obj = sign(data, secret, noSignAttr);
//data['sign'] = obj.sign; //data['sign'] = obj.sign;
return obj; return obj;
} }
getMock(configModule = "dj-car-boutique-work-wechat-miniapp") { getMock(configModule = "dj-car-boutique-work-wechat-miniapp") {
const env = { const env = {
1: "develop", 1: "develop",
2: "test", 2: "test",
3: "production", 3: "production",
4: "beta", 4: "beta",
}[envIndex], }[envIndex],
configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`; configUrl = `https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=${configModule}&env=${env}`;
return new Promise((resolve) => { return new Promise((resolve) => {
wx.request({ wx.request({
url: configUrl, url: configUrl,
data: {}, data: {},
method: "GET", method: "GET",
header: {}, header: {},
dataType: "json", dataType: "json",
responseType: "text", responseType: "text",
success(response) { success(response) {
resolve(response.data); resolve(response.data);
}, },
}); });
}); });
} }
getApiFoxMock(method, params) { getApiFoxMock(method, params) {
return new Promise((resolve) => { return new Promise((resolve) => {
wx.request({ wx.request({
url: `http://127.0.0.1:4523/m1/7739320-7483460-default/rop-scrm-clue/router?method=${method}`, url: `http://127.0.0.1:4523/m1/7739320-7483460-default/rop-scrm-clue/router?method=${method}`,
data: params, data: params,
method: "post", method: "post",
header: { header: {
"content-type": "application/x-www-form-urlencoded", "content-type": "application/x-www-form-urlencoded",
}, },
dataType: "json", dataType: "json",
responseType: "text", responseType: "text",
success(response) { success(response) {
resolve(response.data); resolve(response.data);
}, },
}); });
}); });
} }
} }
export default new Request(); export default new Request();
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!