Explorar o código

自定义上传文件

wuhb hai 2 meses
pai
achega
f79d90bf3f
Modificáronse 1 ficheiros con 52 adicións e 0 borrados
  1. 52 0
      components/upload-image/upload-image.uvue

+ 52 - 0
components/upload-image/upload-image.uvue

@@ -34,6 +34,24 @@
         maxSize?: number // MB
         businessType?: string
     }
+	
+	let cameraInput: HTMLInputElement | null = null
+	const createNativeInput = () => {
+		if (cameraInput) return cameraInput
+		// 创建原生 input 元素
+		cameraInput = document.createElement('input')
+		cameraInput.type = 'file'
+		cameraInput.accept = 'image/*'
+		cameraInput.style.position = 'fixed'
+		cameraInput.style.top = '-1000px'
+		cameraInput.style.left = '-1000px'
+		cameraInput.style.opacity = '0'
+		cameraInput.style.pointerEvents = 'none'
+		cameraInput.setAttribute('capture', 'camera')
+		// 添加到 body
+		document.body.appendChild(cameraInput)
+		return cameraInput
+	}
 
     const props = withDefaults(defineProps<Props>(), {
         modelValue: () => [],
@@ -93,9 +111,43 @@
             uploading.value = false
         }
     }
+	
+	const openCamera = () => {
+	    const input = createNativeInput()
+	    // 清除事件监听器(避免重复绑定)
+	    input.onchange = null
+	    input.onchange = (event: Event) => {
+	        const target = event.target as HTMLInputElement
+	        if (target.files && target.files.length > 0) {
+	            const file = target.files[0]
+	            handleFile(file)
+	        }
+	        // 清除值以便下次选择
+	        input.value = ''
+	    }
+	    // 触发点击
+	    input.click()
+	}
+	
+	const handleFile = (file: File) => {
+		const blobUrl = URL.createObjectURL(file)
+		const result = {
+			tempFilePaths: [blobUrl],  // 类似: blob:http://localhost:8080/550e8400-e29b-41d4-a716-446655440000
+			tempFiles: [{
+				path: blobUrl,
+				size: file.size,
+				name: file.name,
+				type: file.type,
+				lastModified: file.lastModified
+			}]
+		}
+		handleUpload(result.tempFilePaths)
+	}
+
 
     // 选择图片
     const handleChooseImage = (): void => {
+		// let inputHtml = createNativeInput();
         if (imageList.value.length >= props.maxCount) {
             uni.showToast({
                 title: `最多上传${props.maxCount}张图片`,