uniapp 文件下载封装(集成h5及其他端下载)

  • fileUtil.js
/**
 * 下载或预览文件, 需求word和pdf文件直接打开, 其他格式文件进行下载
 * @param {Object} file_url 文件url
 */
export function downloadOrOpenFile(file_url, fileName) {
	let ex = getExtension(file_url)
	if (ex == 'docx' || ex == 'doc' || ex == 'pdf') {

		/* #ifdef H5 */
		console.log('H5端')
		window.open(file_url)
		/*#endif*/

		/*#ifndef  H5*/
		console.log('非H5端')
		uni.openDocument({
			filePath: file_url,
			success: (sus) => {
				console.log('成功打开');
			}
		})
		/*#endif*/

	} else {
		downloadFile(file_url, fileName)
	}

}



/**
 * 下载文件
 */
export function downloadFile(url = '', fileName = '') {
	let token = uni.getStorageSync("token");

	const downloadTask = uni.downloadFile({
		url: url,
		header: {
			token
		},
		success: res => {
			if (res.statusCode === 200) {
				console.log('下载成功');
			}

			/* #ifdef H5 */
			console.log('H5端', res)
			const href = res.tempFilePath
			const box = document.createElement('a')
			box.download = fileName
			box.href = href
			box.click()
			/*#endif*/

			/*#ifndef  H5*/
			console.log('非H5端')
			uni.saveFile({
				tempFilePath: res.tempFilePath,
				success: function(red) {
					uni.showModal({
						title: '提示',
						content: '文件已保存:' + red.savedFilePath,
						cancelText: '我知道了',
						confirmText: '打开文件',
						success: function(res) {
							if (res.confirm) {
								uni.openDocument({
									filePath: red.savedFilePath,
									success: (sus) => {
										console.log('成功打开');
									}
								})
							}
						}
					});
				},
				fail(error) {

				}
			});

			/*#endif*/
		}

	})

	downloadTask.onProgressUpdate((res) => {
		console.log('下载进度:' + res.progress);
		console.log('已下载长度:' + res.totalBytesWritten);
		console.log('文件总长度:' + res.totalBytesExpectedToWrite);
	})
}


// 获取文件扩展名
export function getExtension(filename) {
	if (filename && filename.length > 0) {
		var parts = filename.split('.');
		return parts.length > 0 ? parts[parts.length - 1] : '';
	}
	return ''
}

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐