记录uniapp开发中实现文件下载

1.前端页面下载按钮
<view class="u-body-item u-flex u-row-between u-col-between u-p-b-0">
	<view class="u-body-item-title u-line-2" style="width: 160rpx;">文件</view>
	<text @click="handleRow(tableData,'download')"style="text-align: right;">
<u-icon color="#2979ff" name="download"size="36"></u-icon>下载文件</text>
</view>
2.接口调用,文件下载函数
//调用文件接口
this.http({
						url: 'x-download/fileDownload',
						method: 'post',
						data: {
							Id: id
						},
						responseType: 'blob',
						success: (res) => {
							const data = res.data
							if (res.code == 200) {
								this.$refs.uToast.show({
									title: res.message || res.msg || '下载失败!',
									type: 'warning'
								})

							} else {
								let blobFile = new Blob([data]) // res接口返回的文件流
								let blob = URL.createObjectURL(blobFile)
								//解码文件名
								this.downloads(blob, `文件名${name}`);
							}
						}
					})

// 下载文件函数
			downloads(blob, name) {
				this.$refs.uToast.show({
					title: '文件' + name + '下载中...',
					type: 'success'
				})
				let a = document.createElement('a')
				a.style.display = 'none'
				a.download = name + '.pdf'
				a.href = blob
				a.click()
			},

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐