跨平台应用开发进阶(二十四) :uni-app实现文件下载并保存

x33g5p2x  于2022-06-30 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(818)

一、资源下载

APP应用开发过程中,资源下载是一种常见应用场景。uni-app中应用uni.downloadFile实现文件下载功能。示例代码如下:

  1. downLoadFile() {
  2. const downloadTask = uni.downloadFile({
  3. url: 'http://img.netbian.com/file/2019/0414/7bee7eef5fc44417a0b02a46576e7e16.jpg', //仅为示例,并非真实的资源
  4. success: (res) => {
  5. if (res.statusCode === 200) {
  6. console.log('下载成功');
  7. }
  8. this.dd = res.tempFilePath;
  9. console.log(this.dd);
  10. }
  11. });
  12. downloadTask.onProgressUpdate((res) => {
  13. console.log('下载进度' + res.progress);
  14. console.log('已经下载的数据长度' + res.totalBytesWritten);
  15. console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
  16. });
  17. }

注:文件的临时路径,在应用本次启动期间可以正常使用,如需持久保存,需在主动调用 uni.saveFile,才能在应用下次启动时访问得到。

二、资源保存

当应用uni.downloadFile回调成功后tempFilePath参数代表临时保存文件的路径,再使用uni.saveFile保存到本地即可,实例代码如下:

  1. downLoadFile() {
  2. const downloadTask = uni.downloadFile({
  3. url: 'http://img.netbian.com/file/2019/0414/7bee7eef5fc44417a0b02a46576e7e16.jpg', //仅为示例,并非真实的资源
  4. success: (res) => {
  5. if (res.statusCode === 200) {
  6. console.log('下载成功');
  7. }
  8. let that = this;
  9. uni.saveFile({
  10. tempFilePath: res.tempFilePath,
  11. success: function(red) {
  12. that.luj = red.savedFilePath
  13. console.log(red)
  14. }
  15. });
  16. }
  17. });
  18. downloadTask.onProgressUpdate((res) => {
  19. console.log('下载进度' + res.progress);
  20. console.log('已经下载的数据长度' + res.totalBytesWritten);
  21. console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
  22. });
  23. }

资源下载并保存的位置为:

“内部存储\Android\data\io.dcloud.HBuilder\apps\HBuilder\doc\uniapp_save”

三、资源打开

  1. //文件保存到本地
  2. uni.saveFile({
  3. tempFilePath: data.tempFilePath, //临时路径
  4. success: function(res) {
  5. uni.showToast({
  6. icon: 'none',
  7. mask: true,
  8. title: '文件已保存:' + res.savedFilePath, //保存路径
  9. duration: 3000,
  10. });
  11. setTimeout(() => {
  12. //打开文档查看
  13. uni.openDocument({
  14. filePath: res.savedFilePath,
  15. success: function(res) {
  16. // console.log('打开文档成功');
  17. }
  18. });
  19. }, 3000)
  20. }
  21. });

四、图片保存到本机相册

  1. uni.downloadFile({
  2. url: imgUrl[0],
  3. success: (res) => {
  4. if (res.statusCode === 200) {
  5. //保存图片到系统相册
  6. uni.saveImageToPhotosAlbum({
  7. filePath: res.tempFilePath,
  8. success: function() {
  9. uni.showToast({
  10. title: "保存成功",
  11. icon: "none"
  12. });
  13. return
  14. },
  15. fail: function() {
  16. uni.showToast({
  17. title: "保存失败,请稍后重试",
  18. icon: "none"
  19. });
  20. return
  21. }
  22. });
  23. }
  24. }
  25. })

五、拓展阅读

相关文章