feat: 测试图片分享

This commit is contained in:
2025-11-27 15:55:10 +08:00
parent b6254a231c
commit afc60d3a03
4 changed files with 65 additions and 33 deletions

View File

@@ -120,7 +120,6 @@ export async function shareCurrentPage(title: string, description?: string): Pro
* @param description 分享的描述(可选)
*/
export async function shareImage(imageUrl: string, title: string, description?: string): Promise<void> {
console.log('1',imageUrl,'2',title)
const currentUrl = window.location.href
const text = description
? `${description}\n\n查看图片: ${imageUrl}`
@@ -142,25 +141,29 @@ export async function shareImage(imageUrl: string, title: string, description?:
*/
export async function shareImageFile(imageFile: File, title?: string, text?: string): Promise<void> {
if (!isWebShareSupported()) {
// 如果不支持文件分享,可以尝试将文件转换为 URL 后分享
const imageUrl = URL.createObjectURL(imageFile)
await shareImage(imageUrl, title || '分享图片', text)
URL.revokeObjectURL(imageUrl)
return
throw new Error('WEB_SHARE_UNSUPPORTED')
}
if (typeof navigator.canShare === 'function' && !navigator.canShare({ files: [imageFile] })) {
throw new Error('WEB_SHARE_FILE_UNSUPPORTED')
}
try {
await shareWithWebAPI({
title,
text,
files: [imageFile]
})
} catch (error) {
// 如果分享失败,回退到 URL 方式
const imageUrl = URL.createObjectURL(imageFile)
await shareImage(imageUrl, title || '分享图片', text)
URL.revokeObjectURL(imageUrl)
}
await shareWithWebAPI({
title,
text,
files: [imageFile]
})
}
/**
* 将远程图片转换为 File 对象,便于提前缓存后再触发分享
* @param imageUrl 图片链接
* @param fileName 文件名(可选)
*/
export async function createImageFileFromUrl(imageUrl: string, fileName?: string): Promise<File> {
const response = await fetch(imageUrl)
const blob = await response.blob()
const name = fileName || imageUrl.split('/').pop() || 'share-image.jpg'
return new File([blob], name, { type: blob.type || 'image/jpeg' })
}
/**