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 
相关推荐
怀君13 小时前
Uniapp——View布局生成图片转PDF
pdf·uni-app
2501_9159214313 小时前
uni-app一键生成iOS安装包并上传TestFlight全流程
android·ios·小程序·https·uni-app·iphone·webview
久爱@勿忘13 小时前
uniapp H5 图片压缩并且转blob
前端·javascript·uni-app
Dashingl13 小时前
uni-app 页面传值 报错:TypeError: $t.setAttribute is not a function
前端·javascript·uni-app
大黄说说1 天前
SaaS小程序制作平台对比:码云数智、有赞、微盟
微信小程序
橘子编程1 天前
UniApp跨端开发终极指南
开发语言·vue.js·uni-app
清风絮柳2 天前
65.少儿英语微信小程序
vue.js·spring boot·微信小程序·小程序·毕业设计
tjsoft3 天前
unigui开发微信小程序
微信小程序·小程序
叱咤少帅(少帅)3 天前
Uniapp开发pc端,小程序和APK
小程序·uni-app
2501_915918414 天前
iOS性能测试工具 Instruments、Keymob的使用方法 不局限 FPS
android·ios·小程序·https·uni-app·iphone·webview