uniapp 构建本地txt跨平台小程序、h5、app通用

一般本地构建txt需要上传oss时,需要拿到临时文件地址filePath之类才能进行后续的上传。 但注意不同端使时方式不同

1 wx 是小程序环境的全局对象

arduino 复制代码
// 小程序
#ifdef MP-WEIXIN
// export const createTxt = data => {
//   return new Promise((resolve, reject) => {
//     const fs = wx.getFileSystemManager()
//     const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.txt`
//     fs.writeFile({
//       filePath,
//       data,
//       encoding: 'utf8',
//       success(res) {
//         resolve(filePath)
//       },
//       fail(res) {
//         reject(res)
//       }
//     })
//   })
// }
#endif 

2 网页环境FileURL.createObjectURL 是 Web API);

arduino 复制代码
// 网页输出时
#ifdef H5
// export const createTxt = text => {
//   let file = new File([text], `${Date.now()}`, { type: 'text/plain' })
//   return URL.createObjectURL(file)
// }
#endif

3 app 环境(Android/iOS)用的是 plus 对象,不支持 wx 和 Web API

javascript 复制代码
// app平台专用
#ifdef APP-PLUS
export const createTxt = (data) => {
  return new Promise((resolve, reject) => {
    // 获取应用沙盒目录
    const fileName = `${Date.now()}.txt`;
    plus.io.requestFileSystem(
      plus.io.PRIVATE_DOC, // 沙盒路径,安全可写
      (fs) => {
        fs.root.getFile(
          fileName,
          { create: true },
          (entry) => {
            entry.createWriter((writer) => {
              writer.onwrite = () => resolve(entry.fullPath);
              writer.onerror = reject;
              writer.write(data);
            }, reject);
          },
          reject
        );
      },
      reject
    );
  });
};
#endif 
相关推荐
WangHappy11 小时前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端16 小时前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
Mr_li1 天前
给 Vue 开发者的 uni-app 快速指南
vue.js·uni-app
anyup1 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
icebreaker1 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
Mintopia2 天前
Vue3 项目如何迁移到 uni-app x:从纯 Web 到多端应用的系统指南
uni-app
Mintopia2 天前
uni-app x 发展前景技术分析:跨端统一的新阶段?
uni-app
不爱说话郭德纲3 天前
告别漫长的HbuilderX云打包排队!uni-app x 安卓本地打包保姆级教程(附白屏、包体积过大排坑指南)
android·前端·uni-app
大米饭消灭者4 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro