在小程序中使用formdata上传数据,可实现多文件上传

1.下载formdata

GitHub - zlyboy/wx-formdata: 在小程序中使用formdata上传数据,可实现多文件上传

2. 前端页面

<uni-collapse class='collapse' ref='collapse'>
                <uni-collapse-item v-for="(item, index) in attachmentList"
                :key="index"
                :title="item.dictName" class='collapse-item' title-border='show' :border='false'>
                    <view class="content">
                    <FileUploader  :attachment="item" :uniqueId='uniqueId' @handleHeight='handleHeight' v-model="item.attachmentIds" />
                    </view>
                </uni-collapse-item>
            </uni-collapse>
attachmentList: [
            {
            "id": 1,
            "dictCode": "XCDCTP",
            "dictName": "现场调查图片",
            "categoryCode": ",XCDCTP,",
            "servicePhase": "sb",
            "attachmentIds":[]
            },
        ],
        isFetching: false,
        uniqueId:'',

3.组件

<template>

	<view>
		<view class="file_list">
			<view class="file_list__box" v-for="(file,index) in fileList" :key="index" @click="fileActive(file)">
				<uni-icons type="paperclip" size="15"></uni-icons>
				<text>{
  {file.name}}</text>
				<view class="delete_file" @click.stop="deleteFile(index,file)">
					<uni-icons type="clear" size="16"></uni-icons>
				</view>
			</view>
		</view>
		<view class="uni-file-picker__container">
			<view class="file-picker__box" v-for="(image,index) in imageList" :key="index">
				<view class="file-picker__box-content">
					<image class="file-image" :src="image.url" mode="aspectFill" :data-src="image.url"
						@click.stop="previewImage">
					</image>
					<view class="icon-del-box" @click.stop="deleteImage(index,image)">
						<view class="icon-del"></view>
						<view class="icon-del rotate"></view>
					</view>
				</view>
			</view>
			<view class="file-picker__box" v-for="(video,index) in videoList" :key="index">
				<view class="file-picker__box-content">
					<video class="file-image" :src="video.url"></video>
					<view class="icon-del-box" @click.stop="deleteVideo(index,video)">
						<view class="icon-del"></view>
						<view class="icon-del rotate"></view>
					</view>
				</view>
			</view>
			<view v-if="VideoOfImagesShow" class="file-picker__box">
				<view class="file-picker__box-content is-add" @tap="chooseVideoImage">
					<slot>
						<view class="icon-add"></view>
						<view class="icon-add rotate"></view>
					</slot>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uploadFile,saveAttachInfo,deleteAttachment,uploadFileByName
	} from '@/service/api.js'
	import {
		showToast
	} from '@/utils/index.js'
	import {
		BASE_API_URL
	} from '@/common/config.js'
	import {
		appStorage
	} from '@/utils/storage.js'
	const FormData = require('@/utils/formdata/index.js')
	
	export default {
		props: {
			attachment: Object,
			uniqueId:String
		},
		data() {
			return {
				imageList: [], //图片
				videoList: [], //视频存放
				fileList: [], //文件
				ids: [],
				sourceTypeIndex: 2,
				sourceType: ['拍摄', '相册', '拍摄或相册'],
				VideoOfImagesShow: true,
				cameraList: [{
						value: 'back',
						name: '后置摄像头',
						checked: 'true'
					},
					{
						value: 'front',
						name: '前置摄像头'
					},
				],
				cameraIndex: 0,
				videoSuffix: ["AVI", "mov", "rmvb", "rm", "FLV", "mp4", "3GP"],
				suffix:['jpeg','png','jpg','JPG'],
				pageOfficeSuffix: ['doc', 'docx', 'xls', 'xlsx','pdf','PDF']
			}
		},
		created() {
			this.imageList = []; //图片
			this.videoList = []; //视频存放
			this.fileList = []; //文件

			this.ids = [];
			if(this.attachment.fileList.length>0){
				this.setAttachmentData(this.attachment.fileList)
			}
		},
		watch: {
			ids(val) {
				this.$emit('input', val)
			},
		},
		methods: {
			chooseImages() {
				console.log('图片')
				let that = this;
				// 上传图片
				uni.chooseImage({
					count: 1, //默认9
					// sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: async (response) => {
						console.log(response)
						let result = await that.fileSizeIsLessLimitSize(response.tempFilePaths[0])
						if (result) {
							showToast('图片质量过大')
							return;
						}
						uni.showLoading({
							mask: true
						})
						let igmFile = response.tempFilePaths;
						console.log(igmFile,'igmFile');
						console.log("===============================");
						let requestData = {
							"masterld":'1772150445546708994',
							"formGroupCode":'XMPG',
							"categoryCode":',XCDCTP,',
							"categoryName":'现场图片'
						}
						let token = appStorage.get('token');
						wx.uploadFile({
							url: `接口地址`,
							filePath: igmFile[0],
							name: 'file',
							formData: requestData,
							header: {
								'Blade-Auth': token
							},
							success: res=>{
								console.log(res)
								uni.hideLoading()
								if (res.code === '200') {
									let imgUrls = res.data
									let info = {
										url: BASE_API_URL + '/minio' + imgUrls.link.substring(that.findCharAt(
											imgUrls.link, '/', 2)),
										id: imgUrls.attachmentId
									}
									that.imageList = that.imageList.concat(info);
									that.ids = that.ids.concat(imgUrls.attachmentId);
									that.$emit('handleHeight')
									that.$_saveAttachInfo(imgUrls.attachmentId,imgUrls.link,imgUrls.originalName)
									// if (that.ids.length >= 5) {
									// 	that.VideoOfImagesShow = false;
									// } else {
									// 	that.VideoOfImagesShow = true;
									// }
								} else {
									showToast('操作失败')
								}
							}
						})



					},
				});
			},
    		// importZcExcel(file){
			// 	// console.log('-file:',file,'-fileList:',fileList)
			// 	const formData = new FormData();
			// 	formData.append('excel', file.raw);
			// 	// console.log('文件:',formData);
			// 	let that=this;
			// 	importZc(formData).then(res => {
			// 		let data=res.data;
			// 		// console.log('xxxx:',data)
			// 		if(data && data.success){
			// 					this.$message.success(data.data);
			// 					that.searchChange();
			// 				}else{
			// 					this.$message.error('message:',data.msg);
			// 				}
			// 	});
			// },
			chooseVideoImage() {
				console.log('this.attachment',this.attachment)
				console.log('this.uniqueId',this.uniqueId)
				uni.showActionSheet({
					title: "选择上传类型",
					itemList: ['图片', '视频', '文件'],
					success: (res) => {
						console.log(res)
						if (res.tapIndex == 0) {
							this.chooseImages()
						} else if (res.tapIndex == 1) {
							this.chooseVideo()
						} else {
							this.chooseFile()
						}
					}
				})
			},
			chooseFile() {
				console.log('文件')
				let vm = this;
				wx.chooseMessageFile({
					count: 1,
					type: 'file',
					success: async (response) => {
						console.log('res--选取文件--', response);
						let result = await vm.fileSizeIsLessLimitSize(response.tempFiles[0].path)
						if (result) {
							showToast('文件质量过大')
							return;
						}
						let igmFile = response.tempFiles;
						uni.showLoading({
							mask: true
						})
						let name=igmFile[0].name;
						const [err, res] = await uploadFil
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值