uniapp小程序开发保存临时图片文件到本机(相册)-代码实例

2021-04-01 12:44 阅读:2042

前言:

本文中使用的是uniapp接口开发,微信原生开发请将文中的uni 开头的改为wx 即可。

代码:

/**
 * 保存图片文件到本机
 * @param imageUrl 图片网络路径
 */
export function savePhotoFile(imageUrl){
	return new Promise((resolve, reject) => {
		export_auth();
		function export_auth (){
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success() {
					exportFile();
				},
				fail() {
					modal("提示", '您未授权储存文件,功能将无法使用',"授权","取消").then(res=>{
						uni.openSetting({
							success: (res) => {
								console.log(res.authSetting);
								if (!res.authSetting['scope.writePhotosAlbum']) {
									modal("提示","您未授权储存文件,功能将无法使用");
									reject(res);
								} else {
									exportFile();
								}
							},
							fail: function () {
								reject(res);
							}
						})
					}).catch(err=>{
						reject(err);
					})
				}
			})
		};

		function exportFile(){
			loading("保存中...");
			downloadFile(imageUrl)
				.then(url=>{
					save(url);
				})
				.catch(res=>{
					uni.hideLoading();
					reject(res);
				})
		}

		function save(filePath){
			uni.saveImageToPhotosAlbum({
				filePath: filePath,
				success: (res) => {
					uni.hideLoading();
					resolve(res);
				},
				fail: (err) => {
					uni.hideLoading();
					reject(err);
				}
			})
		}
	})
}

/**
 * 模态弹窗
 * @param title 标题
 * @param cnt 提示内容
 * @param firt 主按钮文字
 * @param cant 次按钮文字(不填则不显示)
 */
export function modal(title, cnt='', firt = '确定', cant = false) {
	return new Promise((resolve, reject) => {
		wx.showModal({
			title: title,
			content: cnt,
			showCancel: cant,
			cancelText: cant ? cant : '',
			cancelColor: '#666666',
			confirmText: firt,
			confirmColor: '#ff5511',
			success: function (data) {
				if (data.confirm) {
					resolve(data);
				} else if (data.cancel) {
					reject(data);
				}
			},
			fail: function (res) {
				reject(res);
			}
		})
	})
};

/**
 * 加载提示
 * @param title 标题
 * @param m 是否显示遮罩
 */
export function loading(title = '加载中...', m = true) {
	return new Promise((resolve, reject) => {
		wx.showLoading({
			title: title,
			mask: m,
			success: function (res) {
				resolve(res);
			},
			fail: function (res) {
				reject(res);
			}
		})
	})
};

/**
 * 下载文件到本地
 * @param {String} url 需要下载的远程链接
 */
export function downloadFile(url){
  return new Promise((resolve, reject) => {
    if (verifyUrl(url)) {
			// url = url.replace("http:","https:");
      wx.downloadFile({
        url: url,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath);
          } else {
            reject(res.errMsg);
          }
        },
        fail(err) {
          reject(err);
        },
      });
    } else {
      // 返回本地地址
      resolve(url);
    }
  });
}

/**
 * 验证是否是网络资源
 * @param {String} url 链接
 */
export function verifyUrl(url){
  var isFormwork = true;//是否是网络资源
  try {
    //判断本地是否存在该文件
    uni.getFileSystemManager().accessSync(url);
    isFormwork = false;
  } catch (error) {
    //判断是否是小程序资源文件
    if (url.indexOf('static/images') >= 0) isFormwork = false;
  }
  return isFormwork;
}

使用:

saveImage(){
    savePhotoFile('文件url地址').then(res=>{
        console.log('保存文件成功');
    }).catch(err=>{
        console.log('保存文件失败');
    })
}

{{commentTotal}} 条评论

{{item.nickname}}
{{item.create_date}}
{{item.content}}
- 上拉或点击加载更多 -
- 加载中 -
- 没有更多了 -
- 本文链接 -