uniapp fetch api cannot load file:///static/model/vosk-model-small-cn-0.22 如何解决?
在uniapp中使用fetch API加载本地文件时遇到问题,报错"cannot load file:///static/model/vosk-model-small-cn-0.22"。这个模型文件已经放在static目录下,但无法通过fetch加载。请问该如何解决这个问题?是路径写法不对还是需要特殊配置?
2 回复
使用相对路径加载模型文件,将模型文件放在static目录下,使用/static/model/...
路径访问。确保文件路径正确且文件存在。
在UniApp中,fetch
API无法加载file://
协议的文件是由于浏览器安全限制导致的。以下是几种解决方案:
1. 将模型文件放在服务器上
- 将
vosk-model-small-cn-0.22
文件夹上传到服务器 - 使用HTTP/HTTPS协议访问:
fetch('https://your-domain.com/static/model/vosk-model-small-cn-0.22/model.json')
2. 使用UniApp的本地文件操作
// 读取本地文件
const modelPath = '/static/model/vosk-model-small-cn-0.22/model.json'
const fileContent = await uni.getFileSystemManager().readFileSync(modelPath, 'utf8')
const modelConfig = JSON.parse(fileContent)
3. 使用UniApp的下载API
// 下载到本地存储
uni.downloadFile({
url: 'https://your-server.com/model.zip',
success: (res) => {
if (res.statusCode === 200) {
const tempFilePath = res.tempFilePath
// 处理下载的文件
}
}
})
4. 配置manifest.json 在H5配置中添加:
{
"h5": {
"devServer": {
"disableHostCheck": true
}
}
}
推荐方案: 建议将模型文件部署到CDN或静态资源服务器,然后通过HTTP请求访问。如果必须在本地使用,可以考虑将模型文件打包到App中,通过相对路径访问。
注意:浏览器环境无法直接访问本地文件系统,这个限制是出于安全考虑。