uniapp如何下载文件,并将文件重命名

下载文件,并将文件重命名

uni.showLoading({
  title: '下载中'
})
 
uni.downloadFile({
  url: "https://192.168.110.225/1.xls",
  success: (downloadResult) => {
    console.log("downloadResult", downloadResult)
    if (downloadResult.statusCode === 200) {
      // 保存文件
      uni.saveFile({
        tempFilePath: downloadResult.tempFilePath,
        success: (saveResult) => {
          uni.hideLoading();
          console.log('文件保存成功,保存路径:', saveResult.savedFilePath);
          const oldFilePath = saveResult.savedFilePath;
          const fileExtension = oldFilePath.split('.').pop();
 
          // 创建一个Date对象
          const now = new Date();
 
          // 获取当前的年、月、日
          const year = now.getFullYear();
          const month = now.getMonth() + 1; // 月份是从0开始的,需要加1
          const date = now.getDate();
 
          const hours = now.getHours().toString().padStart(2, '0');
          const minutes = now.getMinutes().toString().padStart(2, '0');
          const seconds = now.getSeconds().toString().padStart(2, '0');
 
          const newFileName = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + '_结果.xls'; //
          新的文件名
          const newFilePath = oldFilePath.replace(/[^\/]*$/, newFileName);
 
          uni.showToast({
            icon: 'none',
            mask: true,
            title: `文件已保存`, //保存路径
            duration: 3000,
          });
          console.log("newFilePath", oldFilePath, newFilePath)
          // 修改文件名
          plus.io.resolveLocalFileSystemURL(oldFilePath, entry => {
            entry.getParent(_oldFile => {
              entry.moveTo(_oldFile, '/' + newFileName, newFilePath => {
                console.log('newFilePath', newFilePath.fullPath)
              })
            })
          })
        },
        fail: (saveError) => {
          console.error('文件保存失败:', saveError);
        }
      });
    } else {
      console.error('文件下载失败,状态码:', downloadResult.statusCode);
    }
  },
  fail: (downloadError) => {
    console.error('文件下载失败:', downloadError);
  }
});