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 
相关推荐
文心快码BaiduComate17 小时前
用Comate Zulu开发一款微信小程序
前端·后端·微信小程序
CHB19 小时前
uni-ai:让你的App快速接入AI
uni-app·deepseek
小徐_23333 天前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
iOS阿玮3 天前
永远不要站在用户的对立面,挑战大众的公知。
uni-app·app·apple
xw53 天前
uni-app中v-if使用”异常”
前端·uni-app
!win !3 天前
uni-app中v-if使用”异常”
前端·uni-app
Emma歌小白3 天前
如何首次运行小程序后端
微信小程序
赣州云智科技的技术铺子3 天前
【一步步开发AI运动APP】十二、自定义扩展新运动项目1
微信小程序·小程序·云开发·智能小程序
2501_915918413 天前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张3 天前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview