当前位置: 首页 > article >正文

uniapp有关MD5文件上传的方法

         请求的Api:

// 合同管理 - 详情 - 附件上传
export function saveAttachmentListApi(data){
  return request({
    url: `/api/supplychain/StandardOnline/saveAttachmentList`,
    method: 'POST',
    data
  })
}

 

// 附件上传
export function chunkMergesOnly(data){
  return request({
    url: `/api/file/mergeAttachmentOnly`,
    method: 'POST',
    data
  })
}
<template>
	<view>
		<u-toast ref="uToast"></u-toast>
		<u-popup v-model="viewVisible" @close="close" mode="center" border-radius="14">
			<view class="usingSealsClass">
				<view class="topTitle">
					<text>合同文件上传</text>
				</view>
				<view class="bottomArea">
					<ss-upload ref="ssUpload" width="260rpx" height="100rpx" @uploadFilepProgress='uploadFilepProgress'
						@uploadSuccess="onuploadSuccess" :uploadOptions="uploadOptions" :isUploadServer="isUploadServer"
						@getFile='getFile'>
						<button class="selectFileClass" @click="uploadFile">上传附件</button>
					</ss-upload>
					<!-- 上传进度条 -->
					<view class="material-sent" v-if="flieProgress !== 0">
						<progress class="select-tips" :percent="flieProgress" stroke-width="4" activeColor="	#19be6b" />
						<view class="tips-text">
							上传进度{{flieProgress}}%
						</view>
					</view>
					<view class="uploadTip">
						<text>注:只能上传"ZIP"类型的文件,压缩包的名称必须为合同号</text>
					</view>
				</view>

				<view class="buttonClass">
					<button size="default" type="default"
						style="width: 100px;height:30px;margin:0px;margin-right:10px;fontSize:14px;lineHeight:30px;color:#ffffff;backgroundColor: #ff5555;border:1px solid  #ff5555"
						@click="cancelClick">取消</button>
					<button size="default" type="default"
						style="width: 100px;height:30px;margin:0px;margin-right:16px;fontSize:14px;lineHeight:30px;color:#ffffff;backgroundColor:#1890ff;border:1px solid #1890ff"
						@click="confirmClick">提交</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		saveAttachmentListApi,
		chunkMergesOnly
	} from '@/api/apply/standardPlatformApi'
	import SparkMD5 from 'spark-md5';
	export default {
		props: ['config'],
		mounted() {
			this.viewVisible = true;
			this.serverParams.businessIds = [this.config.id];
			this.serverParams.contractNumbers = [this.config.row[0]['CONTRACT_NUMBER']];
		},
		data() {
			return {
				flieProgress: 0,
				isUploadServer: true,
				serverParams: {}, // 业务接口需要的参数
				viewVisible: false,
				uploadOptions: {
					url: this.define.baseURL + '/api/file/chunk',
					name: 'file',
					header: {
						'Authorization': uni.getStorageSync("token")
					},
					formData: {
						chunkNumber: 1,
						chunkSize: 0,
						currentChunkSize: 0,
						totalSize: 0,
						identifier: '',
						filename: '',
						relativePath: '',
						totalChunks: 1,
						fileType: 'application/x-zip-compressed',
						extension: 'zip',
					}
				}
			}
		},
		methods: {
			confirmClick() {
				saveAttachmentListApi(this.serverParams).then(res => {
					if (res.code == 200) {
						this.$refs.uToast.show({
							type: 'success',
							title: '附件上传成功!'
						})
						setTimeout(() => {
							this.viewVisible = false;
							this.$emit('closeCustomDialog', false)
						}, 1000)
					} else {
						this.$refs.uToast.show({
							type: 'error',
							icon: false,
							title: '附件上传失败!',
						})
					}
				}).catch(err => {

				})
			},
			// 上传成功
			onuploadSuccess(e, data) {
				console.log(data,'DADA')
				let extension = this.getFileExtension(data[0].name).extension
				let fileName = this.getFileExtension(data[0].name).currentFileName
				if (extension !== 'zip') {
					this.flieProgress = 0
					this.$refs.uToast.show({
						type: 'warning',
						title: '请上传"ZIP"类型的文件',
						icon: false,
						duration: 3000
					})
					return
				}
				if(fileName !== this.serverParams.contractNumbers) {
					this.flieProgress = 0
					this.$refs.uToast.show({
						type: 'warning',
						title: `当前上传文件名称:【${fileName}】\n当前合同号:【${this.serverParams.contractNumbers}】\n上传的文件名称须为当前合同号,请重新上传!`,
						icon: false,
						duration: 5000
					})
					return
				}
				const form = new FormData()
				form.append('identifier', this.uploadOptions.formData.identifier)
				form.append('fileName', this.uploadOptions.formData.filename)
				form.append('fileSize', this.uploadOptions.formData.totalSize)
				form.append('fileType', 'x-zip-compressed')
				form.append('extension', 'zip')
				form.append('type', 'annex')
				form.append('pathType', 'defaultPath')
				form.append('isAccount', '0')
				form.append('folder', '')
				form.append('moduleId', '')
				form.append('tableName', '')
				form.append('onlineSignature', '1')
				form.append('businessType', '')
				form.append('businessIds', this.serverParams.businessIds)
				form.append('contractNumbers', this.serverParams.contractNumbers)
				let formDataStr = '';
				form.forEach((value, key) => {
					if (formDataStr !== '') {
						formDataStr += '&';
					}
					formDataStr += encodeURIComponent(key) + '=' + encodeURIComponent(value);
				});
				uni.request({
					url: this.define.baseURL + '/api/file/mergeAttachmentOnly',
					method: 'POST',
					data: formDataStr,
					header: {
						'content-type': 'application/x-www-form-urlencoded',
					},
					success: (res) => {
						setTimeout(() => {
							this.flieProgress = 0
							this.$refs.uToast.show({
								type: 'success',
								title: `"${this.uploadOptions.formData.filename}"压缩包成功上传,请点击提交按钮!`,
								icon: false,
								duration:3000
							})
						},500)
						this.serverParams = res.data
					},
					fail: (err) => {
						console.error('请求失败', err);
					}
				});
			},
			close() {
				this.viewVisible = false;
				this.$emit('closeCustomDialog', true)
			},
			cancelClick() {
				this.viewVisible = false;
				this.$emit('closeCustomDialog', true)
			},
			uploadFile() {
				setTimeout(() => {
					this.$refs.ssUpload.uploadFile()
				})
			},
			computeMD5(file) {
				const spark = new SparkMD5.ArrayBuffer()
				const md5 = spark.end()
				this.computeMD5Success(md5)
			},
			computeMD5Success(md5, file) {
				this.uploadOptions.formData.identifier = md5 // 把md5值作为文件的识别码
			},
			getFile(e) {
				this.computeMD5()
				this.uploadOptions.formData.chunkSize = e.tempFiles[0].size
				this.uploadOptions.formData.currentChunkSize = e.tempFiles[0].size
				this.uploadOptions.formData.totalSize = e.tempFiles[0].size
				this.uploadOptions.formData.filename = e.tempFiles[0].name
				this.uploadOptions.formData.relativePath = e.tempFiles[0].name
			},
			getFileExtension(fileName) {
				// 使用 split 方法将文件名按 '.' 分割成数组
				const parts = fileName.split('.');
				// 数组的最后一个元素就是文件的后缀
				const extension = parts[parts.length - 1];
				const currentFileName = parts[0]
				return {extension,currentFileName}
			},
			// 上传文件的回调事件 - 值为:上传进度
			uploadFilepProgress(value) {
				this.flieProgress = value
			}
		}
	}
</script>

<style lang="scss" scoped>
	

	::v-deep .zb-table {
		height: 95% !important;
	}

	.usingSealsClass {
		width: 700rpx;
		height: 400rpx;
		position: relative;

		.topTitle {
			width: 100%;
			height: 80rpx;
			text-align: center;
			border-bottom: 1px dashed lightgrey;
			line-height: 75rpx;
		}

		.bottomArea {
			margin-top: 5px;
			width: 100%;
			height: calc(100% - 90px);
			position: relative;

			.uploadTip {
				position: absolute;
				top: 70px;
				left: 18px;
				color: red;
				font-size: 12px;
			}
			.material-sent {
				width: 189rpx;
				background: rgba(245, 245, 245, 0.5);
				position: absolute;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				top: 72%;
				.select-tips {
					width: 130rpx;
					height: 10rpx;
					margin-bottom: 12rpx;
				}
			
				.tips-text {
					font-size: 24rpx;
					color: #028DE3;
				}
			}
		}

		.buttonClass {
			position: absolute;
			bottom: 10px;
			width: 100%;
			display: flex;
			justify-content: flex-end;
			align-items: center;
		}
	}
</style>


http://www.kler.cn/a/381133.html

相关文章:

  • # 起步专用 - 哔哩哔哩全模块超还原设计!(内含接口文档、数据库设计)
  • 一个比RTK或redux更轻量级更易使用的 React 第三方状态管理工具库的配置与使用
  • jsp中的四个域对象(Spring MVC)
  • 【QSS样式表 - ⑥】:QPushButton控件样式
  • 程控电阻箱应用中需要注意哪些安全事项?
  • 【086】基于51单片机电子音乐门铃【Proteus仿真+Keil程序+报告+原理图】
  • Vue3里抽离公共模块进行封装然后通过Vue进行调取
  • 字节面试Java基础部分——HashMap
  • QT 如何使QLabel的文字垂直显示
  • 弹性裸金属服务器和传统裸金属服务器有什么区别?
  • 自制inscode项目推荐:色块小游戏
  • 截图工具 for Linux --- 你用过吗?
  • operator[ ]和迭代器,auto,for流,reserve
  • 【测试小白--如何写好测试用例--测试用例编写的方法+结合常见登录模块为实例--保姆级教学】
  • vue通过iframe方式嵌套grafana图表
  • ENSP (虚拟路由冗余协议)VRRP配置
  • 基于Matlab的语音识别
  • 仿真APP助力汽车零部件厂商打造核心竞争力
  • MySQL表的增删改查(CRUD3约束)
  • HTTP请求和请求体Body
  • 【Oracle】空格单字符通配符查询匹配失败
  • 【PMP】学习总结
  • FreeMarker模版引擎入门及实战
  • 人工智能学习--归一化(Normalization)
  • 编译工具与文件学习(一)-YAML、repos、vcstoolcolcon
  • 【大模型LLM面试合集】大语言模型架构_chatglm系列模型