uni-app文件上传

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uni-app文件上传相关的知识,希望对你有一定的参考价值。

参考技术A 使用uview框架上传,具体的方法就是使用uni.uploadFile()方法上传

```

<template>

<view style="color: #6e6e6e;">

<view class="u-p-t-30 u-p-b-10">

上传图片:

</view>

<!-- <u-upload :action="action" :file-list="fileList"></u-upload> -->

<u-upload :before-upload="beforeUpload"></u-upload>

</view>

</template>

<script>

export default

data()

return

,

onLoad: function(options)

// console.log(options);

,

methods:

beforeUpload(index, list)

console.log(list[index]);

uni.uploadFile(

url: '---------------',// api地址

filePath: list[index].url, // 本地上传完成后的路径

name: 'file', // 默认

header:

"Content-Type": "multipart/form-data", // formdata提交格式

"Authorization": 'Bearer ' + uni.getStorageSync('token') // token验证

,

formData:   // 其他的formdata参数

fileType: '2',

fileContainerName: 'default'

,

success: function(uploadFileRes)

console.log('success', JSON.parse(uploadFileRes.data));



);







</script>

<style lang="scss">

</style>

```

uni-app 113上传文件请求封装

chat.vue

<template>
	<view>
		<!-- 导航栏 -->
		<free-nav-bar :title="detail.name" :noreadnum="totalNoreadnum" showBack>
			<free-icon-button slot="right"><text class="iconfont font-md" @click="openChat">&#xe6fd;</text>
			</free-icon-button>
		</free-nav-bar>
		<!-- 聊天内容区域 -->
		<scroll-view scroll-y="true" class="bg-light position-fixed left-0 right-0" style="box-sizing:border-box;bottom:105rpx;"
			:style="chatBodyBottom" :scroll-into-view="scrollIntoView" :show-scrollbar="false"
			:scroll-with-animation="true">

			<!-- 聊天信息列表组件 -->
			<view v-for="(item,index) in list" :key="index" :id="'chatItem_'+index">
				<free-chat-item :item="item" :index="index" ref="chatItem"
					:pretime=" index > 0 ? list[index-1].create_time : 0" @long="long" :shownickname="currentChatItem.shownickname"
					@preview="previewImage" >
				</free-chat-item>
			</view>
		</scroll-view>

		<!-- 扩展菜单 -->
		<free-popup ref="action" bottom transformOrigin="center bottom" @hide="keyBoardHeight = 0" :mask="false">
			<view style="height: 580rpx;" class="border-top border-light-secondary">
				<swiper :indicator-dots="emoticonOrActionList.length>1" style="height:510rpx;">
					<swiper-item class="row" v-for="(item,index) in emoticonOrActionList" :key="index">
						<view class="col-3 flex flex-column align-center justify-center" style="height: 255rpx;"
							v-for="(item2,index2) in item" :key="index2" @click="actionEvent(item2)">
							<image :src="item2.icon" mode="widthFix" style="width: 100rpx;height: 100rpx;"></image>
							<text class="font-sm text-muted mt-2">item2.name</text>
						</view>
					</swiper-item>
				</swiper>
			</view>
		</free-popup>
		<!-- 弹出层 -->
		<free-popup ref="extend" maskColor bottom :bodyWidth="240" :bodyHeight="geMenusHeight" :tabbarHeight="105">
			<view class="flex flex-column" style="width:240rpx;" :style="getMenusStyle">
				<view v-for="(item,index) in menusList" :key="index" class="flex-1 flex align-center"
					hover-class="bg-light" @click="clickEvent(item.event)">
					<text class="font-md pl-3">item.name</text>
				</view>
			</view>
		</free-popup>
		<!-- #ifdef APP-PLUS-NVUE -->
		<div class="position-fixed top-0 right-0 left-0 bottom-0" v-if="mode==='action' || mode==='emoticon'"
			@click="clickPage" :style="'bottom:'+maskBottom+'px;'"></div>
		<!-- #endif -->

		<!-- 底部输入框 -->
		<view class="position-fixed left-0 right-0 border-top flex align-center"
			style="background-color: #F7F7F6;height: 105rpx;" :style="'bottom:'+keyBoardHeight+'px;'">
			<free-icon-button @click="changeVoiceOrText">
				<block v-if="mode === 'audio'">
					<text class="iconfont font-lg">&#xe607;</text>
				</block>
				<block v-else>
					<text class="iconfont font-lg">&#xe606;</text>
				</block>
			</free-icon-button>
			<view class="flex-1">
				<view v-if="mode==='audio'" class="rounded flex align-center justify-center" style="height: 80rpx;"
					:class="isRecording?'bg-hover-light':'bg-white'" @touchstart="voiceTouchStart"
					@touchend="voiceTouchEnd" @touchmove="voiceTouchMove" @touchcancel="voiceTouchCancel">
					<text class="font">isRecording ? '松开 结束' : '按住 说话'</text>
				</view>
				<!-- 底部输入框 -->
				<textarea v-else fixed class="bg-white rounded p-2 font-md" style="height: 50rpx;max-width: 450rpx;"
					:adjust-position="false" v-model="text" @focus="mode = 'text'" />
				<!-- @click="onInputClick" -->
				<!-- <textarea v-else class="bg-white rounded p-1 font-md" style="height: 50rpx;max-width: 500rpx;"
					:adjust-position="false" v-model="text" @focus="mode = 'text'"  /> -->
			</view>

			<template v-if="text.length === 0">
				<!-- 表情 -->
				<free-icon-button><text class="iconfont font-lg"
						@click="openActionOrEmoticon('emoticon')">&#xe605;</text></free-icon-button>
				<!-- 扩展菜单 -->
				<free-icon-button @click="openActionOrEmoticon('action')"><text class="iconfont font-lg">&#xe603;</text>
				</free-icon-button>
			</template>
			<view v-else class="flex-shrink">
				<!-- 发送按钮 -->
				<!-- <view class="main-bg-color rounded flex align-center justify-center mr-2 px-2 pt-4" style="height: 70rpx;" @click="send('text')"> 发送
				</view> -->
				<free-main-button name="发送" @click="send('text')"></free-main-button>
			</view>
		</view>

		<!-- 录音提示 -->
		<view v-if="isRecording" class="position-fixed top-0 left-0 right-0 flex align-center justify-center"
			style="bottom: 105rpx;">
			<view class="rounded flex flex-column align-center justify-center"
				style="width: 360rpx;height: 360rpx;background-color: rgba(0,0,0,0.5);">
				<image src="/static/images/audio/audio/recording.gif" style="width: 150rpx;height: 150rpx;"></image>
				<text class="font text-white mt-3">unRecord?'松开手指,取消发送':'手指上滑,取消发送'</text>
			</view>
		</view>
	</view>
</template>
<script>
	// #ifdef APP-NVUE
	const domModule = weex.requireModule('dom');
	// #endif
	import freeNavBar from '@/components/free-ui/free-nav-bar.vue';
	import freeIconButton from '@/components/free-ui/free-icon-button.vue';
	import freeChatItem from '@/components/free-ui/free-chat-item.vue';
	import freePopup from '@/components/free-ui/free-popup.vue';
	import freeMainButton from '@/components/free-ui/free-main-button.vue';
	import 
		mapState,
		mapMutations
	 from 'vuex';
	import auth from '@/common/mixin/auth.js';
	import $U from '@/common/free-lib/util.js';
	import $H from '@/common/free-lib/request.js';
	export default 
		mixins: [auth],
		components: 
			freeNavBar,
			freeIconButton,
			freeChatItem,
			freePopup,
			freeMainButton
		,
		watch: 
			mode(newValue, oldValue) 

				if (newValue !== 'action' && newValue !== 'emoticon') 
					this.$refs.action.hide();
				

				if (newValue !== 'text') 
					uni.hideKeyboard()
				
			
		,
		// 生命周期
		mounted() 
			this.statusBarHeight = 0;
			// 获取任务栏高度
			// #ifdef APP-PLUS-NVUE
			this.statusBarHeight = plus.navigator.getStatusbarHeight()
			// #endif
			this.navBarHeight = this.statusBarHeight + uni.upx2px(90)
			// 监听键盘高度变化
			uni.onKeyboardHeightChange((res) => 
				if (this.mode !== 'action' && this.mode !== 'emoticon') 
					this.keyBoardHeight = res.height;
				
				if (this.keyBoardHeight > 0) 
					this.pageToBottom()
				
			)
			// 注册发送音频事件
			this.regSendVoiceEvent((url) => 
				if (!this.unRecord) 
					// 发送
					this.send('audio', url, 
						time: this.RecordTime
					)
				
			);
		,
		onLoad(e) 
			if (!e.params) 
				return this.backToast();
			
			// 初始化
			this.__init();
			this.detail = JSON.parse(e.params)

			// 创建聊天对象
			this.chat.createChatObject(this.detail)

			// 获取历史记录
			this.list = this.chat.getChatdetail()
			// 监听接收聊天信息
			uni.$on('onMessage', (message) => 
				if ((message.from_id === this.detail.id && message.chat_type === 'user') || (message.chat_type ===
						'group' && this.detail.id)) 
					this.list.push(message);
					// 置于顶部
					this.pageToBottom();
				
			)

			// uni.$on('updateHistory', this.updateHistory)
			// this.pageToBottom()
			uni.$on('clearHistory',()=>
				this.list = [];
			)
		,
		destroyed() 
			// 销毁聊天对象
			this.chat.destoryChatObject();
			// 销毁监听接收聊天消息
			uni.$off('onMessage', () => )
			uni.$off('clearHistory', () => )
		,
		computed: 
			...mapState(
				chatList:state=>state.user.chatList,
				RECORD: state => state.audio.RECORD,
				RecordTime: state => state.audio.RecordTime,
				chat: state => state.user.chat,
				totalNoreadnum: state => state.user.totalNoreadnum
			),
			// 当前会话配置信息
			currentChatItem()
				let index = this.chatList.findIndex(item=>item.id === this.detail.id && item.chat_type === this.detail.chat_type);
				if(index !== -1)
					return this.chatList[index]
				
				return ;
			,
			// 所有信息的图片地址
			imageList() 
				var arr = [];
				this.list.forEach((item) => 
					if (item.type === 'emoticon' || item.type === 'image') 
						arr.push(item.data)
					
				)
				return arr;
			,
			// 获取蒙版的位置
			maskBottom() 
				return this.keyBoardHeight + uni.upx2px(105)
			,
			// 动态获取菜单高度
			geMenusHeight() 
				let H = 100;
				return this.menus.length * H;
			,
			// 获取菜单的样式
			getMenusStyle() 
				return `height:$this.geMenusHeightrpx;`;
			,
			// 是否是本人
			isdoSelf() 
				// 获取本人id(假设拿到了)
				let id = 1
				let user_id = this.propIndex > -1 ? this.list[this.propIndex].user_id : 0
				return user_id === id
			,
			// 获取操作菜单
			menusList() 
				return this.menus.filter(v => 
					if (v.name === '撤回' && this.isDoSelf) 
						return false;
					 else 
						return true;
					
				)
			,
			// 聊天区域bottom
			chatBodyBottom() 
				return `bottom:$uni.upx2px(105) + this.keyBoardHeightpx;top:$this.navBarHeightpx`;
			,
			// 获取操作或者表情列表
			emoticonOrActionList() 
				if (this.mode === 'emoticon' || this.mode === 'action') 
					return this[this.mode + 'List'];
				 else 
					return [];
				
			
		,
		data() 
			return 
				// 模式 text输入文字 emoticon表情 action操作 audio音频
				mode: 'text',
				scrollIntoView: "",
				// 扩展菜单列表
				actionList: [
					[
							name: "相册",
							icon: "/static/images/extends/pic.png",
							event: "uploadImage"
						,
						
							name: "拍摄",
							icon: "/static/images/extends/vid

以上是关于uni-app文件上传的主要内容,如果未能解决你的问题,请参考以下文章

uni-app实现文件上传功能

uni-app 微信小程序 上传图片 文件 uni.uploadFile() 、 uni.chooseImage()

uni-app 113上传文件请求封装

uni-app 112上传文件和oss配置

uni-app上传头像/更改头像

uni-app调用原生的文件系统管理器(可选取附件上传)