uniapp在H5端实现PDF和视频的上传、预览、下载
作者:mmseoamin日期:2024-01-25

上传

uniapp在H5端实现PDF和视频的上传、预览、下载,在这里插入图片描述,第1张

上传页面

		
          
        
        只能上传视频和pdf文件(支持.pdf, .mp4, .avi, .ts)
        
          
            
            
            {{ item.split('-')[item.split('-').length - 1] }}
          
          
        
import { uploadFile } from '../../common/common'
upload() {
   uploadFile(6).then(res => {
      console.log(2222, res)
      this.form.ququ6 = this.form.ququ6.concat(res)
   })
},

上传方法

/**
 * 上传视频和pdf文件
 * @param {*} count 个数
 * @returns arr-- 最终结果   ['img','img']
 */
export let uploadFile = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseFile({
			count: count,
			extension: ['.pdf', '.mp4', '.avi', '.ts'],
			success: function (res) {
				uni.showLoading({
					title: '上传中'
				})
				let imgarr = res.tempFilePaths
				let arr = []
				imgarr.forEach(item => {
					uni.uploadFile({
						url: '/prod-api' + '/file/upload',
						filePath: item,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token') || ''
						},
						success: (res) => {
							console.log(JSON.parse(res.data))
							arr.push(JSON.parse(res.data).data.url)
							if (arr.length == imgarr.length) {
								uni.hideLoading()
								let arr1 = arr.filter(item => ['pdf', 'mp4', 'avi', 'ts'].includes(item.split('.')[item.split('.').length - 1]))
								if (arr1.length != arr.length) {
									uni.showToast({
										title: '只能上传视频和pdf文件',
										icon: 'none'
									})
								}
								resolve(arr1)
							}
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			}
		});
	})
}

整个页面静态



预览和下载

uniapp在H5端实现PDF和视频的上传、预览、下载,在这里插入图片描述,第2张

预览页面 PDF预览详见

 附件记录
    
      
        
        
        {{ item.split('-')[item.split('-').length - 1] }}
      
      下载
    
 data() {
    return {
      form: {
        ququ6: ["https://cscec83-learnplatform.oss-cn-shanghai.aliyuncs.com/test/2023-11-27/6a12b9ca-3ae9-435b-b023-0f9c119afad3-1.mp4", "https://cscec83-learnplatform.oss-cn-shanghai.aliyuncs.com/test/2023-11-27/53aa1f60-0735-4203-86b2-c2b8b019e8d9-我的哈哈.pdf"]
      }
    }
  },
 preview(item) {
      if (item.split('.')[item.split('.').length - 1] == 'pdf') {
        uni.navigateTo({
          url: '/pages/course/pdf?url=' + item
        })
      } else {
        // uni.navigateTo({
        //   url: '/pages/course/video?url=' + item
        // })
        window.open(item)
      }
    },
    downLoad(url) {
      if (url.split('.')[url.split('.').length - 1] == 'pdf') {
        window.open(url)
      } else {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob'; // 返回类型blob
        xhr.onload = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            let blob = this.response;
            // 转换一个blob链接
            let u = window.URL.createObjectURL(new Blob([blob]));
            let a = document.createElement('a');
            a.download = url.split('-')[url.split('-').length - 1]; //下载后保存的名称
            a.href = u;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            a.remove();
            uni.hideLoading();
          }
        };
        xhr.send()
      }
    },

详情页面静态



完整的上传视频、上传pdf、上传图片 方法封装(需要传递name、size、时长)

/**
 *  上传图片
 *  count-- 可选张数
 * 	arr-- 最终结果   ['img','img']
 */
export let upload = (count = 1) => {
	console.log(count);
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: count,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
			success: function (res) {
				uni.showLoading({
					title: '上传中'
				})
				let imgarr = res.tempFilePaths
				let arr = []
				imgarr.forEach(item => {
					uni.uploadFile({
						url: '/prod-api' + '/file/upload',
						filePath: item,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token') || ''
						},
						success: (res) => {
							console.log(JSON.parse(res.data))
							uni.hideLoading()
							arr.push(JSON.parse(res.data).data.url)
							if (arr.length == imgarr.length) {
								resolve(arr)
							}
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			}
		});
	})
}
/**
 * 上传pdf文件
 * @param {*} count 个数
 * @returns arr-- 最终结果   ['img','img']
 */
export let uploadFile = (count = 1) => {
	return new Promise((resolve, reject) => {
		uni.chooseFile({
			count: count,
			extension: ['.pdf'],
			success: function (res) {
				console.log(888, res)
				uni.showLoading({
					title: '上传中'
				})
				let imgarr = res.tempFiles
				let arr = []
				imgarr.forEach(item => {
					uni.uploadFile({
						url: '/prod-api' + '/file/appUpload', //接口地址
						filePath: item.path, // 上传文件参数值
						name: 'file', // 上传文件参数名
						formData: {  // 额外参数
							fileName: item.name,
							size: (item.size / 1024 / 1024).toFixed(2),
							type: 'pdf',
						},
						header: { //请求头
							Authorization: uni.getStorageSync('token') || ''
						},
						success: (res) => {
							arr.push(JSON.parse(res.data).data)
							if (arr.length == imgarr.length) {
								uni.hideLoading()
								let arr1 = arr.filter(item => 'pdf' == item.fileName.split('.')[item.fileName.split('.').length - 1])
								if (arr1.length != arr.length) {
									uni.showToast({
										title: '只能上传pdf文件',
										icon: 'none'
									})
								}
								resolve(arr1)
							}
						},
						fail: () => {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					});
				})
			}
		});
	})
}
/** 上传视频
 * 	arr-- 最终结果   [{img1:'全路径',img2:'半路径'},{img1:'全路径',img2:'半路径'}]
 */
export let uploadVideo = () => {
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			count: 1,
			success: function (res) {
				uni.showLoading({
					title: '上传中'
				})
				console.log(111111111111, res)
				uni.uploadFile({
					url: '/prod-api' + '/file/appUpload', //接口地址
					filePath: res.tempFilePath, // 上传文件参数值
					name: 'file', // 上传文件参数名
					formData: {  // 额外参数,formData传参
						fileName: res.name,
						size: (res.size / 1024 / 1024).toFixed(2),
						duration: res.duration,
						type: 'video',
					},
					header: { //请求头
						Authorization: uni.getStorageSync('token') || ''
					},
					success: (res) => {
						uni.hideLoading()
						if (JSON.parse(res.data).code == '200') {
							resolve(JSON.parse(res.data).data)
						} else {
							uni.showToast({
								title: JSON.parse(res.data).msg,
								icon: 'none'
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: '上传失败,请重试',
							icon: 'none'
						})
					}
				});
			}
		});
	})
}