合伙人端和门店端微信SDK调用相机复原

This commit is contained in:
2026-08-02 16:34:56 +08:00
parent 205c1110c2
commit ca6fa2244b
5 changed files with 238 additions and 14 deletions
@@ -1,6 +1,8 @@
import { useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { uploadFileToOss, type OssMediaType } from '../lib/upload';
import { enqueueUpload } from '../lib/upload-lock';
import { formatChooseImageFailMessage } from '@dukang/weixin-sdk';
import { isWechatEnv, weixinSdk } from '../lib/weixin';
import { toastError } from '../lib/toast';
type OssUploadFieldProps = {
@@ -12,10 +14,27 @@ type OssUploadFieldProps = {
wide?: boolean;
compact?: boolean;
label?: string;
/** 兼容现有调用:选图不再依赖 openId 绑定 */
wechatReady?: boolean;
onWechatReadyChange?: (ready: boolean) => void;
};
const DEFAULT_MAX_MB = 10;
function formatWechatUploadError(e: unknown): string {
const msg = e instanceof Error ? e.message : '无法打开相册';
const formatted = formatChooseImageFailMessage(msg);
if (formatted) return formatted;
if (/invalid signature/i.test(msg)) {
return '微信 JSSDK 签名校验失败:请确认公众号已配置 JS 接口安全域名,并刷新页面后重试';
}
return msg;
}
function acceptsImages(accept: string) {
return accept.includes('image');
}
export default function OssUploadField({
value,
onChange,
@@ -29,6 +48,7 @@ export default function OssUploadField({
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState('');
const [showAlbumFallback, setShowAlbumFallback] = useState(false);
function showUploadError(text: string) {
setError(text);
@@ -37,6 +57,17 @@ export default function OssUploadField({
const resolvedAccept =
accept ?? (mediaType === 'VIDEO' ? 'video/*' : mediaType === 'FILE' ? 'image/*,.pdf' : 'image/*');
const inWechat = isWechatEnv();
const useWechatPicker =
inWechat && (mediaType === 'IMAGE' || (mediaType === 'FILE' && acceptsImages(resolvedAccept)));
useEffect(() => {
if (!useWechatPicker) return;
weixinSdk.reset();
void weixinSdk.init().catch(() => {
/* 点击上传时会再次初始化 */
});
}, [useWechatPicker]);
async function persistUpload(file: File) {
if (!file.size) {
@@ -64,21 +95,60 @@ export default function OssUploadField({
}
}
function pickFile() {
async function pickWechatImage() {
setUploading(true);
setError('');
try {
weixinSdk.reset();
await weixinSdk.init();
// 选图 + 上传须在同一个队列任务内完成,避免嵌套 enqueueUpload 死锁
await enqueueUpload(async () => {
const files = await weixinSdk.chooseImages({
count: 1,
sourceType: ['album', 'camera'],
});
if (!files?.[0]) return;
await persistUpload(files[0]);
});
} catch (e) {
const msg = e instanceof Error ? e.message : '无法打开相册';
if (/cancel/i.test(msg)) return;
throw e;
} finally {
setUploading(false);
}
}
async function pickFile() {
if (uploading) return;
setError('');
if (useWechatPicker) {
try {
await pickWechatImage();
} catch (e) {
const msg = e instanceof Error ? e.message : '无法打开相册';
if (/cancel/i.test(msg)) return;
const formatted = formatWechatUploadError(e);
setError(`${formatted},可改从系统相册选择`);
setShowAlbumFallback(true);
inputRef.current?.click();
}
return;
}
inputRef.current?.click();
}
const isImage = mediaType === 'IMAGE' && value;
const isFile = mediaType === 'FILE' && value;
const busy = uploading;
const pickerLabel = label ?? (mediaType === 'IMAGE' ? '从系统相册选择' : '点击上传');
const pickerLabel = label ?? (useWechatPicker ? '拍照 / 从相册选择' : '点击上传');
const triggerProps = {
type: 'button' as const,
disabled: busy,
onClick: pickFile,
onClick: () => void pickFile(),
};
return (
@@ -92,6 +162,7 @@ export default function OssUploadField({
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
setShowAlbumFallback(false);
void uploadSelectedFile(file);
}
}}
@@ -120,13 +191,24 @@ export default function OssUploadField({
className={`partner-upload-dashed${wide ? ' partner-upload-dashed--wide' : ''}${compact ? ' partner-upload-dashed--compact' : ''}`}
>
<span className="material-symbols-outlined text-primary" style={{ fontSize: compact ? 28 : 36 }}>
{busy ? 'hourglass_top' : 'photo_library'}
{busy ? 'hourglass_top' : 'add_a_photo'}
</span>
<span className="text-primary" style={{ fontWeight: 500 }}>
{uploading ? '上传中…' : pickerLabel}
</span>
</button>
)}
{showAlbumFallback && useWechatPicker && (
<button
type="button"
className="partner-btn-outline"
style={{ marginTop: 8, width: '100%' }}
disabled={busy}
onClick={() => inputRef.current?.click()}
>
</button>
)}
{error && <p className="partner-form-error" role="alert">{error}</p>}
</div>
);