uniapp导入文件
uniapp 导入文件的几种方法
通过 <input type="file"> 选择文件
在模板中添加文件选择输入框,监听 change 事件获取文件对象。
<template>
<input type="file" @change="handleFileChange" />
</template>
methods: {
handleFileChange(e) {
const file = e.target.files[0];
console.log('Selected file:', file);
}
}
使用 uni.chooseFile API uniapp 提供了跨平台的文件选择 API,支持多选和文件类型过滤。
uni.chooseFile({
count: 1, // 选择文件数量
type: 'all', // 文件类型 all/image/video
success: (res) => {
console.log('File path:', res.tempFilePaths[0]);
}
});
通过 uni.uploadFile 上传文件 选择文件后可直接上传到服务器。
uni.chooseFile({
success: (res) => {
uni.uploadFile({
url: 'https://example.com/upload',
filePath: res.tempFilePaths[0],
name: 'file',
success: (uploadRes) => {
console.log('Upload success:', uploadRes.data);
}
});
}
});
读取文件内容 对于文本类文件,可使用 uni.getFileSystemManager 读取内容。
const fs = uni.getFileSystemManager();
fs.readFile({
filePath: 'file_path',
encoding: 'utf8',
success: (res) => {
console.log('File content:', res.data);
}
});
注意事项
- 小程序平台有临时文件路径限制,需注意文件生命周期
- H5 平台支持标准 File API,功能更全面
- 安卓/iOS 需处理权限问题,部分接口需要真机调试







