uniapp多格式文件选择(APP,H5)【补充】

时间:2025-01-30 13:59:24
<template> <view class="content"> <button @click="fileChoose">文件选择</button> <view :fileData="fileData" :change:fileData=""/> <view style="word-break:break-all;">文件路径:{{filePath}}</view> </view> </template> <script> export default { data() { return { fileData: '', filePath: '', fileName: '' } }, onLoad() { }, methods: { fileChoose(){ this.fileData = 'test' setTimeout(()=> { this.fileData = '' },1000) }, async receiveRenderFile(result){ // #ifdef APP-PLUS const fileUrl = await this.base64toPath(result.filePath, result.name); this.fileName = fileUrl.relativePath this.filePath = fileUrl.localAbsolutePath // #endif // #ifdef H5 this.fileName = result.name this.filePath = result.filePath // #endif console.log('选择文件的路径:'+this.filePath) }, //将base64转成路径 async base64toPath(base64, attachName) { console.log('base64开始转化成文件') let _that = this; return new Promise(function(resolve, reject) { const filePath = `_doc/yourFilePath/${attachName}`; plus.io.resolveLocalFileSystemURL('_doc', function(entry) { entry.getDirectory("yourFilePath", { create: true, exclusive: false, }, function(entry) { entry.getFile(attachName, { create: true, exclusive: false, }, function(entry) { entry.createWriter(function(writer) { writer.onwrite = function(res) { console.log('base64转化文件完成') const obj = { relativePath: filePath, localAbsolutePath: plus.io .convertLocalFileSystemURL( filePath) } resolve(obj); } writer.onerror = reject; writer.seek(0); writer.writeAsBinary(_that .getSymbolAfterString(base64, ',')); }, reject) }, reject) }, reject) }, reject) }) }, // 取某个符号后面的字符 getSymbolAfterString(val, symbolStr) { if (val == undefined || val == null || val == "") { return ""; } val = val.toString(); const index = val.indexOf(symbolStr); if (index != -1) { val = val.substring(index + 1, val.length); return val; } else { return val } } } } </script> <script module="renderJS" lang="renderjs"> export default { data() { return {} }, mounted() { console.log('mounted') }, methods: { receiveFileData(newValue, oldValue, ownerVm, vm){ if(!newValue){ return } this.createFileInputDom(ownerVm) }, createFileInputDom(ownerVm){ let fileInput = document.createElement('input') fileInput.setAttribute('type','file') fileInput.setAttribute('accept','*') fileInput.click() fileInput.addEventListener('change', e => { let file = e.target.files[0] // #ifdef APP-PLUS console.log('开始读取文件') let reader = new FileReader(); //读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 reader.readAsDataURL(file); reader.onload = function(event) { const base64Str = event.target.result; // 文件的base64 console.log('文件读取完成') //如果文件较大,这里调用到逻辑层可能时间较长 ownerVm.callMethod('receiveRenderFile', { name: file.name, filePath: base64Str }) } // #endif // #ifdef H5 const filePath = URL.createObjectURL(file) ownerVm.callMethod('receiveRenderFile',{ name: file.name, filePath: filePath }) // #endif }) } } } </script> <style> </style>