유니앱 프로젝트 실습 요약 (13) Encapsulation 파일 운용 방법

소개: 일상적인 APP 개발 과정에서는 파일 저장, 목록 읽기, 파일 보기 및 삭제 등이 필요한 경우가 많습니다. 다음으로 구체적인 방법을 살펴보겠습니다.

목차

  • 원리분석
  • 메소드 구현
  • 실습
  • 케이스 디스플레이

원리분석

주로 다음 API입니다.

  • uni.saveFile: 파일을 로컬 캐시 목록에 저장합니다.
  • uni.getSavedFileList: 저장된 파일 목록을 가져옵니다.
  • uni.getSavedFileInfo: 파일 세부정보를 가져옵니다.
  • uni.removeSavedFile:저장된 파일을 제거합니다.
  • uni.openDocument: 문서를 엽니다.

다음 메서드는 루트 디렉터리의 scripts폴더에 있는 파일에 저장됩니다 http.js.

메소드 구현

다음으로 데이터 요청, 파일 다운로드, 파일 업로드의 메소드 캡슐화를 구현하는 방법을 하나씩 설명하겠습니다.

문서 저장

조건부 컴파일을 사용하여 여기에 파일을 저장하고 해당 메서드는 h5, WeChat 애플릿 및 APP에 대해 각각 캡슐화됩니다.

  • 전반적인 접근 방식

여기서는 주로 기본 매개변수, 수신 매개변수, 병합 매개변수를 포함한 매개변수를 다룹니다.

// 保存图片
async function saveFile(options) {
    
    
  let isHttp = options.url.indexOf("http") > -1;
  let url = isHttp ? options.url : `${
      
      urls.baseUrl}${
      
      options.url}`;
  let defultOptions = {
    
    
    url,
    name: options.name || utils.uuid(),
    extName: options.extName || utils.fileExt(url),
    filePath: options.filePath,
  };
  let params = {
    
     ...options, ...defultOptions };
  console.log("保存文件参数:", params);

  // h5代码

  // 微信小程序代码

  // APP 代码
}
  • h5 세이브 파일

이는 주로 fetchAPI를 사용하여 파일을 다운로드한 다음 a태그를 사용하여 클릭하여 다운로드합니다.

// #ifdef H5
fetch(url, {
    
    
  mode: "cors",
})
  .then(async (res) => {
    
    
    const e = await res.blob();
    return e;
  })
  .then((blob) => {
    
    
    const fileElem = document.createElement("a");
    let fileUrl = URL.createObjectURL(blob);
    fileElem.style.display = "none";
    fileElem.href = fileUrl;
    fileElem.download = `${
      
      params.name}.${
      
      params.extName}`;
    document.body.appendChild(fileElem);
    fileElem.click();
    setTimeout(() => {
    
    
      URL.revokeObjectURL(fileUrl);
      fileElem.remove();
    }, 1000);
  });
// #endif
  • WeChat 애플릿은 파일을 저장합니다

이는 주로 WeChat 애플릿의 API를 사용하여 wx.getFileSystemManager파일 관리자 인터페이스를 얻은 다음 파일을 다운로드하고 저장합니다.

// #ifdef MP-WEIXIN
const fs = wx.getFileSystemManager(),
  userDataPath = wx.env.USER_DATA_PATH;
const filePath = params.filePath || `${
      
      userDataPath}/${
      
      params.name}.${
      
      params.extName}`;
wx.showLoading({
    
    
  title: "文件下载中...",
});
wx.downloadFile({
    
    
  url,
  success(res) {
    
    
    let tempFile = res.tempFilePath;
    let img = ["png", "jpg", "gif"];
    if (tempFile && img.includes(params.extName)) {
    
    
      wx.saveImageToPhotosAlbum({
    
    
        filePath: tempFile,
        success: function () {
    
    
          wx.showToast({
    
    
            title: "保存成功!",
            icon: "success",
          });
        },
        fail() {
    
    
          wx.showToast({
    
    
            title: "保存失败!",
            icon: "error",
          });
        },
      });
    } else {
    
    
      fs.saveFile({
    
    
        tempFilePath: tempFile,
        filePath,
        success: function () {
    
    
          wx.showToast({
    
    
            title: "保存成功!",
            icon: "success",
          });
        },
        fail() {
    
    
          wx.showToast({
    
    
            title: "保存失败!",
            icon: "error",
          });
        },
      });
    }
  },
  fail() {
    
    
    wx.showToast({
    
    
      title: "下载失败!",
      icon: "error",
    });
  },
  complete() {
    
    
    wx.hideLoading();
  },
});
// #endif
  • 앱 저장 파일

여기서 주요 방법은 uni.saveFile파일을 저장하는 것입니다.

// #ifdef APP-PLUS
uni.showLoading({
    
    
  title: "文件下载中...",
});
let opts = {
    
    
  url,
};
let data = await download(opts);
if (data) {
    
    
  uni.saveFile({
    
    
    tempFilePath: data,
    success: function (res) {
    
    
      uni.showToast({
    
    
        title: "保存成功!",
        icon: "success",
      });
    },
    fail() {
    
    
      uni.showToast({
    
    
        title: "保存失败!",
        icon: "error",
      });
    },
    complete() {
    
    
      uni.hideLoading();
    },
  });
} else {
    
    
  uni.showToast({
    
    
    title: "下载失败!",
    icon: "error",
  });
}
// #endif

파일 관리 받기

다음은 getIfs특정 터미널에서 파일 관리 방법을 얻기 위해 사용되는 캡슐화된 방법이다.

// utils.js
// 文件操作
function getIfs() {
    
    
  let ifs = {
    
    
    list: null,
    info: null,
    delete: null,
    open: null,
  };
  // #ifdef MP-WEIXIN
  let fsm = wx.getFileSystemManager();
  ifs.list = fsm.getSavedFileList;
  ifs.info = fsm.getFileInfo;
  ifs.delete = fsm.unlink;
  ifs.open = fsm.open;
  // #endif
  // #ifdef APP-PLUS
  ifs.list = uni.getSavedFileList;
  ifs.info = uni.getSavedFileInfo;
  ifs.delete = uni.removeSavedFile;
  ifs.open = uni.openDocument;
  // #endif
  return ifs;
}

파일 목록

이는 특정 파일 정보를 얻기 위해 파일 경로를 전달하는 것을 지원합니다.

// 保存文件列表
async function fileList(filePath) {
    
    
  try {
    
    
    let ifs = utils.getIfs(),
      list = [];
    let data = await ifs.list();
    if (data.fileList) {
    
    
      list = data.fileList;
      if (list.length) {
    
    
        for (let item of list) {
    
    
          item.name = utils.fileName(item.filePath);
          item.id = utils.uuid();
          item.sizeText = utils.fileSize(item.size);
          item.timeText = utils.nowDate(item.createTime).normal;
        }
      }
      if (filePath) {
    
    
        list = list.filter((s) => filePath === s.filePath);
      }
      return {
    
    
        code: 1,
        data: list,
      };
    } else {
    
    
      return {
    
    
        code: 2,
        data: data.errMsg,
      };
    }
  } catch (e) {
    
    
    //TODO handle the exception
    return {
    
    
      code: 2,
      data: e,
    };
  }
}

파일 보기

// 打开文件
async function openFile(filePath = "", showMenu = true) {
    
    
  try {
    
    
    if (!filePath) {
    
    
      return {
    
    
        code: 2,
        data: "文件路径不能为空!",
      };
    }
    let ifs = utils.getIfs();
    let result = await ifs.open({
    
    
      filePath,
      showMenu,
    });
    if (result) {
    
    
      return {
    
    
        code: 1,
        data: "打开成功!",
      };
    } else {
    
    
      return {
    
    
        code: 2,
        data: "打开失败!",
      };
    }
  } catch (e) {
    
    
    //TODO handle the exception
    return {
    
    
      code: 2,
      data: e,
    };
  }
}

파일 삭제

// 删除文件
async function deleteFile(filePath) {
    
    
  try {
    
    
    if (!filePath) {
    
    
      return {
    
    
        code: 2,
        data: "文件路径不能为空!",
      };
    }
    let ifs = utils.getIfs();
    let result = await ifs.delete({
    
    
      filePath,
    });
    if (result) {
    
    
      return {
    
    
        code: 1,
        data: "删除成功!",
      };
    } else {
    
    
      return {
    
    
        code: 2,
        data: "删除失败!",
      };
    }
  } catch (e) {
    
    
    //TODO handle the exception
    return {
    
    
      code: 2,
      data: e,
    };
  }
}

작성한 후에는 메서드를 내보내는 것을 잊지 마세요.

실습

템플릿 내용

  • 문서 저장
<button type="primary" size="mini" @click="saveFile('file')" v-if="httpInfo.uploadFileUrl">
  保存文件
</button>
  • 파일 목록
<!-- #ifdef APP-PLUS -->
<view class="list-http">
  <button @click="getFileList">文件列表</button>
  <text class="list-http-txt">响应内容:</text>
  <view class="list-file" v-for="(item, index) in httpInfo.fileList" :key="item.id">
    <view class="list-file-item">文件名称:{
   
   { item.name }}</view>
    <view class="list-file-item">文件大小:{
   
   { item.sizeText }}</view>
    <view class="list-file-item">文件路径:{
   
   { item.filePath }}</view>
    <view class="list-file-item">保存时间:{
   
   { item.timeText }}</view>
    <view class="list-file-item">
      <button size="mini" type="primary" @click="openFile(item)">查看文件</button>
      <button size="mini" type="warn" @click="delFile(item, index)">删除文件</button>
    </view>
  </view>
</view>
<!-- #endif -->

각본 방법

  • 데이터 정의
let httpInfo = reactive({
    
    
  fileList: [],
});
  • 문서 저장
// 保存文件
function saveFile(type = "img") {
    
    
  let url = httpInfo[type == "img" ? "uploadImgUrl" : "uploadFileUrl"];
  if (url) {
    
    
    console.log("要保存的文件:", url);
    proxy.$http.saveFile({
    
    
      url,
      name: httpInfo.fileName,
    });
  }
}
  • 파일 목록
// #ifdef APP-PLUS
// 获取文件列表
async function getFileList() {
    
    
  let filePath = "_doc/uniapp_save/16928451309592.srt";
  let data = await proxy.$http.fileList();
  if (data.code == 1) {
    
    
    httpInfo.fileList = data.data;
  }
}
// #endif
  • 파일 보기
// #ifdef APP-PLUS
// 查看文件
async function openFile(item) {
    
    
  let data = await proxy.$http.openFile(item.filePath);
  console.log("查看文件结果:", data);
}

// #endif
  • 파일 삭제
// #ifdef APP-PLUS
// 删除文件
async function delFile(item, index) {
    
    
  let data = await proxy.$http.deleteFile(item.filePath);
  if (data.code === 1) {
    
    
    httpInfo.fileList.splice(index, 1);
    uni.showToast({
    
    
      title: data.data,
      icon: "success",
    });
  } else {
    
    
    uni.showToast({
    
    
      title: data.data,
      icon: "error",
    });
  }
}
// #endif

케이스 디스플레이

  • 파일 보기
    여기에 이미지 설명을 삽입하세요.

  • 파일 삭제
    여기에 이미지 설명을 삽입하세요.

마침내

위 내용은 Encapsulation 파일 운용방법의 주요 내용인데, 부족한 부분이 있으면 수정 부탁드립니다.

추천

출처blog.csdn.net/fed_guanqi/article/details/132767265