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);
} }
...@@ -883,7 +883,12 @@ Page({ ...@@ -883,7 +883,12 @@ Page({
// 确保 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
);
// 处理地区显示格式:确保是 "省份 城市" 格式 // 处理地区显示格式:确保是 "省份 城市" 格式
// 车辆所在地 // 车辆所在地
......
import api from "~/api/api"; import api from "~/api/api";
import { uploadFile } from "~/utils/oss/ossUpload.js";
const IMG_URL = const IMG_URL =
"https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/"; "https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/";
...@@ -215,7 +215,10 @@ Component({ ...@@ -215,7 +215,10 @@ Component({
.filter((file) => { .filter((file) => {
// 过滤掉没有 url 的文件 // 过滤掉没有 url 的文件
if (!file || !file.url) { if (!file || !file.url) {
console.warn("initImageList - 过滤掉无效文件(url 为空):", file); console.warn(
"initImageList - 过滤掉无效文件(url 为空):",
file
);
return false; return false;
} }
return true; return true;
...@@ -324,7 +327,7 @@ Component({ ...@@ -324,7 +327,7 @@ Component({
}, },
// 上传单个文件 // 上传单个文件
uploadSingleFile(file, key, label) { async uploadSingleFile(file, key, label) {
// 如果 file 是数组,取第一个元素 // 如果 file 是数组,取第一个元素
if (Array.isArray(file)) { if (Array.isArray(file)) {
if (file.length === 0) { if (file.length === 0) {
...@@ -397,35 +400,18 @@ Component({ ...@@ -397,35 +400,18 @@ Component({
}); });
const uploadType = ext === "unknown" ? "jpg" : ext; const uploadType = ext === "unknown" ? "jpg" : ext;
// 读取文件为 base64 console.log(file);
wx.getFileSystemManager().readFile({ const url = await uploadFile(file);
filePath: filePath, console.log(url);
encoding: "base64",
success: (res) => {
const base64Data = `${uploadType}@${res.data}`;
// 调用上传接口
api[requestEvent]({
file: base64Data,
})
.then((result) => {
console.log("上传结果:", result);
if (result.code === 0 || result.code === "0") {
const uploadedUrl = result.data;
// 更新该文件的状态为完成
const { imageList } = this.data;
const currentList = imageList[key] || [];
const newList = [...currentList]; const newList = [...currentList];
// 对于视频,保存 videoUrl、coverUrl 和 isVideo 标识 // 对于视频,保存 videoUrl、coverUrl 和 isVideo 标识
// van-uploader 对于视频文件,需要使用 coverUrl 作为预览图 // van-uploader 对于视频文件,需要使用 coverUrl 作为预览图
if (fileType == "video") { if (fileType == "video") {
newList[fileIndex] = { newList[fileIndex] = {
url: uploadedUrl.videoUrl, // 视频 URL url: url,
thumb: uploadedUrl.coverUrl, // 封面图(van-uploader 使用 thumb 作为预览图) thumb: url + (url.indexOf("?") >= 0 ? "&" : "?") + "x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast",
coverUrl: uploadedUrl.coverUrl, // 保存封面图 URL,用于预览 coverUrl: url + (url.indexOf("?") >= 0 ? "&" : "?") + "x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast",
isVideo: true, isVideo: true,
name: label, name: label,
key: key, key: key,
...@@ -433,7 +419,7 @@ Component({ ...@@ -433,7 +419,7 @@ Component({
}; };
} else { } else {
newList[fileIndex] = { newList[fileIndex] = {
url: uploadedUrl, url: url,
isVideo: false, isVideo: false,
name: label, name: label,
key: key, key: key,
...@@ -456,71 +442,6 @@ Component({ ...@@ -456,71 +442,6 @@ Component({
icon: "success", icon: "success",
duration: 2000, duration: 2000,
}); });
} else {
// 上传失败,更新状态
const { imageList } = this.data;
const currentList = imageList[key] || [];
const newList = [...currentList];
newList[fileIndex] = {
...newList[fileIndex],
status: "failed",
message: "上传失败",
};
this.setData({
[`imageList.${key}`]: newList,
});
wx.showToast({
title: result.message || "上传失败",
icon: "none",
duration: 2000,
});
}
})
.catch((err) => {
console.error("上传失败:", err);
// 上传失败,更新状态
const { imageList } = this.data;
const currentList = imageList[key] || [];
const newList = [...currentList];
newList[fileIndex] = {
...newList[fileIndex],
status: "failed",
message: "上传失败",
};
this.setData({
[`imageList.${key}`]: newList,
});
wx.showToast({
title: "上传失败,请重试",
icon: "none",
duration: 2000,
});
});
},
fail: (err) => {
console.error("读取文件失败:", err);
// 读取失败,移除该文件
const { imageList } = this.data;
const currentList = imageList[key] || [];
const newList = currentList.filter((_, i) => i !== fileIndex);
this.setData({
[`imageList.${key}`]: newList,
});
wx.showToast({
title: "读取文件失败",
icon: "none",
duration: 2000,
});
},
});
}, },
// 处理删除 // 处理删除
...@@ -643,7 +564,7 @@ Component({ ...@@ -643,7 +564,7 @@ Component({
}); });
}, },
// 批量上传视频文件 // 批量上传视频文件(使用 OSS uploadFile)
async uploadVideoFiles(tempFiles, field, requestEvent, fileType) { async uploadVideoFiles(tempFiles, field, requestEvent, fileType) {
wx.showLoading({ wx.showLoading({
title: "上传中", title: "上传中",
...@@ -652,68 +573,44 @@ Component({ ...@@ -652,68 +573,44 @@ Component({
try { try {
const { imageList } = this.data; const { imageList } = this.data;
const currentList = imageList[field.key] || []; let currentList = imageList[field.key] || [];
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,
size: item.size,
// 读取文件为 base64 };
const _res = await new Promise((resolve, reject) => { const url = await uploadFile(fileObj);
wx.getFileSystemManager().readFile({
filePath: val,
encoding: "base64",
success: resolve,
fail: reject,
});
});
// 上传文件
const img = await api[requestEvent]({
file: `${uploadType}@${_res.data}`,
});
const { code, data, message } = img;
if (code == 0) {
// 添加到列表
const newFile = const newFile =
fileType == "video" fileType == "video"
? { ? {
url: data.videoUrl, url,
thumb: data.coverUrl, thumb: url + (url.indexOf("?") >= 0 ? "&" : "?") + "x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast",
coverUrl: data.coverUrl, coverUrl: url + (url.indexOf("?") >= 0 ? "&" : "?") + "x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast",
isVideo: true, isVideo: true,
name: field.label, name: field.label,
key: field.key, key: field.key,
status: "done", status: "done",
} }
: { : {
url: data, url,
isVideo: false, isVideo: false,
name: field.label, name: field.label,
key: field.key, key: field.key,
status: "done", status: "done",
}; };
const newList = [...currentList, newFile]; currentList = [...currentList, newFile];
this.setData( this.setData(
{ {
[`imageList.${field.key}`]: newList, [`imageList.${field.key}`]: currentList,
}, },
() => { () => {
// 同步到页面数据
this.syncToPage(); this.syncToPage();
} }
); );
} else {
wx.hideLoading();
wx.showToast({
title: message || "上传失败",
icon: "none",
});
return;
}
} }
wx.hideLoading(); wx.hideLoading();
...@@ -790,10 +687,16 @@ Component({ ...@@ -790,10 +687,16 @@ Component({
.filter((item) => !item.isVideo) .filter((item) => !item.isVideo)
.map((item) => item.url); .map((item) => item.url);
const currentIndex = imageUrls.findIndex((url) => url === fileUrl); const currentIndex = imageUrls.findIndex((url) => url === fileUrl);
console.log(fileUrl, "fileUrl");
wx.previewImage({ wx.previewImage({
current: fileUrl, current: fileUrl,
urls: imageUrls, urls: imageUrls,
success: () => {
console.log("success");
},
fail: () => {
console.log("fail");
},
}); });
} }
}, },
...@@ -878,7 +781,14 @@ Component({ ...@@ -878,7 +781,14 @@ Component({
// 校验必填项 // 校验必填项
validate() { validate() {
const { imageList, uploadFields, uploadCertificateFields, uploadVideoFields, uploadReportFields, uploadOtherFields } = this.data; const {
imageList,
uploadFields,
uploadCertificateFields,
uploadVideoFields,
uploadReportFields,
uploadOtherFields,
} = this.data;
// 合并所有字段 // 合并所有字段
const allFields = [ const allFields = [
...@@ -892,7 +802,9 @@ Component({ ...@@ -892,7 +802,9 @@ Component({
// 1. 检查是否有正在上传的文件 // 1. 检查是否有正在上传的文件
for (let field of allFields) { for (let field of allFields) {
const list = imageList[field.key] || []; const list = imageList[field.key] || [];
const uploadingFiles = list.filter(file => file.status === 'uploading'); const uploadingFiles = list.filter(
(file) => file.status === "uploading"
);
if (uploadingFiles.length > 0) { if (uploadingFiles.length > 0) {
return { return {
message: `${field.label}正在上传中,请稍候...`, message: `${field.label}正在上传中,请稍候...`,
...@@ -903,10 +815,12 @@ Component({ ...@@ -903,10 +815,12 @@ Component({
// 2. 检查必填的车辆图片(只检查状态为 done 的文件) // 2. 检查必填的车辆图片(只检查状态为 done 的文件)
for (let field of uploadFields) { for (let field of uploadFields) {
if (field.required) { if (field.required) {
console.log(imageList[field.key], 'imageList[field.key]'); console.log(imageList[field.key], "imageList[field.key]");
const list = imageList[field.key] || []; const list = imageList[field.key] || [];
// 只统计上传完成的文件 // 只统计上传完成的文件
const doneFiles = list.filter(file => !file.status || file.status === 'done'); const doneFiles = list.filter(
(file) => !file.status || file.status === "done"
);
if (doneFiles.length === 0) { if (doneFiles.length === 0) {
return { return {
message: `请上传${field.label}`, message: `请上传${field.label}`,
......
<!-- 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, // 选择图片返回的相对路径 const url = await uploadFile(fileObj)
encoding: 'base64', // 编码格式 _this.data[type][index].uploadImages?.push({url, isVideo: false})
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({ _this.setData({
[`${type}`]: _this.data[type], [`${type}`]: _this.data[type],
[`formData.${field.key}`]: _this.data[type][index].uploadImages?.map(val => { return val.url })?.join(',') [`formData.${field.key}`]: _this.data[type][index].uploadImages?.map(val => val.url)?.join(',')
}) })
} else {
wx.$util.showToast(message)
}
} }
} 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, // 选择图片返回的相对路径 const videoUrl = await uploadFile(fileObj)
encoding: 'base64', // 编码格式 const coverUrl = videoUrl + '&x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
success: resolve, _this.data[type][index].uploadImages?.push({url: videoUrl, isVideo: true, coverUrl})
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({ _this.setData({
[`${type}`]: _this.data[type], [`${type}`]: _this.data[type],
[`formData.${field.key}`]: data.videoUrl [`formData.${field.key}`]: videoUrl
}) })
} else {
wx.$util.showToast(message)
}
} }
} 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', // 编码格式
success: resolve,
fail: reject
})
})
const img = await api[requestEvent]({
file: `${uploadType}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
if (fileType == 'video') { if (fileType == 'video') {
_this.data[type][index].uploadImages?.push({url: data.videoUrl, isVideo: true, coverUrl: data.coverUrl}) const coverUrl = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
_this.data[type][index].uploadImages?.push({url, isVideo: true, coverUrl})
} else { } else {
_this.data[type][index].uploadImages?.push({url: data, isVideo: false}) _this.data[type][index].uploadImages?.push({url, isVideo: false})
} }
_this.setData({ _this.setData({
[`${type}`]: _this.data[type], [`${type}`]: _this.data[type],
[`formData.${field.key}`]: fileType == 'video' ? data.videoUrl : _this.data[type][index].uploadImages?.map(val => { return val.url })?.join(',') [`formData.${field.key}`]: fileType == 'video' ? url : _this.data[type][index].uploadImages?.map(val => val.url)?.join(',')
}) })
} else {
wx.hideLoading()
wx.$util.showToast(message)
}
} }
} 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,22 +763,12 @@ Page({ ...@@ -762,22 +763,12 @@ 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', // 编码格式
success: resolve,
fail: reject
})
})
const img = await api.uploadImg({
file: `${type}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
_this.setData({ _this.setData({
[`formData.${field}`]: data [`formData.${field}`]: data
}) })
...@@ -788,9 +779,6 @@ Page({ ...@@ -788,9 +779,6 @@ Page({
[`formData.${field}`]: orgLicenseImages?.join(',') [`formData.${field}`]: orgLicenseImages?.join(',')
}) })
} }
} else {
wx.$util.showToast(message)
}
} }
} catch (error) { } catch (error) {
wx.$util.showToast("上传失败,请重试") wx.$util.showToast("上传失败,请重试")
...@@ -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, // 选择图片返回的相对路径 const videoUrl = await uploadFile(fileObj)
encoding: 'base64', // 编码格式 const coverUrl = videoUrl + (videoUrl.indexOf('?') >= 0 ? '&' : '?') + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
success: resolve,
fail: reject
})
})
const img = await api.uploadFileWithCover({
file: `${type}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
_this.setData({ _this.setData({
'formData.thirdPartyTransactionVoucher': data.videoUrl, 'formData.thirdPartyTransactionVoucher': videoUrl,
thirdPartyTransactionType: 'video', thirdPartyTransactionType: 'video',
thirdPartyTransactionCoverUrl: data?.coverUrl thirdPartyTransactionCoverUrl: coverUrl
}) })
} else {
wx.$util.showToast(message)
}
} }
} 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', // 编码格式
success: resolve,
fail: reject
})
})
const img = await api[requestEvent]({
file: `${type}@${_res.data}`
})
const { code, data, message } = img
if (code == 0) {
if (fileType == 'video') { if (fileType == 'video') {
const coverUrl = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast'
_this.setData({ _this.setData({
['formData.thirdPartyTransactionType']: 'video', ['formData.thirdPartyTransactionType']: 'video',
[`formData.${field}`]: url,
thirdPartyTransactionType: res.type,
thirdPartyTransactionCoverUrl: coverUrl
}) })
} } else {
_this.setData({
[`formData.${field}`]: fileType == 'video' ? data.videoUrl : data,
})
if (field == 'thirdPartyTransactionVoucher') {
_this.setData({ _this.setData({
thirdPartyTransactionType: res.type, [`formData.${field}`]: url,
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) {
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
"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;
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!