uview-ui使用表单u-upload图片上传

1、效果图

2、页面代码

<template>
	<view class="box">
		<!-- 注意,如果需要兼容微信小程序,最好通过setRules方法设置rules规则 -->
		<u--form labelWidth="120" labelPosition="top" labelAlign="left" :labelStyle="{'fontSize':'14px'}" 
		:model="guideline" ref="uForm" :rules="rules">
			<u-form-item label="标题" prop="guidelineTitle" ref="guidelineTitle">
				<u--input v-model="guideline.guidelineTitle" placeholder="请输入标题"></u--input>
			</u-form-item>
			<u-form-item label="图片">
				<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple 
				:maxCount="6" :previewFullImage="true"></u-upload>
			</u-form-item>

			<u-form-item label="简介" prop="guidelineContent">
				<u-textarea v-model="guideline.guidelineContent" style="width: 100%;" placeholder="请输入详情"
				 height="200" maxlength="20000">
				</u-textarea>
			</u-form-item>
		</u--form>

		<view style="padding-bottom: 20px;padding-top: 10px;">
			<u-row>
				<u-col :span="6">
					<u-button type="primary" @click="submit" size="big" :text="articleId?'确认修改':'发布'">
					</u-button>
				</u-col>
				<u-col :span="6">
					<u-button style="margin-top: 20px;" type="error " @click="resetForm" size="big" text="重置">
					</u-button>
				</u-col>
			</u-row>
		</view>

		<u-notify ref="uNotify" message="Hi uview-plus"></u-notify>
	</view>
</template>

<script>
	import { addGuideline, getGuideline, updateGuideline } from '@/api/tourism/guideline.js';

	export default {
		data() {
			return {
				redirect: '/pages/tourism-tabbar/guideline/index',
				show: false,
				guidelineId: null,
				guideline: {},
				spotId: null,
				comboId: null,
				fileList: [],
				rules: {
					'guidelineTitle': {
						required: true,
						message: "标题不能为空",
						trigger: "blur"
					}
				}
			};
		},

		onLoad(option) {
			if (option && option.spotId) {
				this.spotId = option.spotId;
			}

			if (option && option.comboId) {
				this.comboId = option.comboId;
			}

			this.getGuidelineInfo();
		},

		onReady() {
			// 微信小程序需要用此写法设置校验规则
			//this.$refs.uForm.setRules(this.rules)
		},

		methods: {
			getGuidelineInfo() {
				if (!this.guidelineId) {
					return
				}
				getGuideline(this.guidelineId).then(res => {
					if (res.code == 200) {
						this.guideline = res.data;

						this.fileList = [];
						for (let i = 0; i < JSON.parse(this.guideline.pictures).length; i++) {
							this.fileList.push({
								url: JSON.parse(this.guideline.pictures)[i]
							})
						}
					}
				})
			},
			submit() {
				//this.$refs.uForm.validate().then(valid => {

					const list = [];
					for (let i = 0; i < this.fileList.length; i++) {
						list.push(this.fileList[i].url)
					}
					this.guideline.pictures = JSON.stringify(list)

					if (this.guideline.guidelineId != null) {
						updateGuideline(this.guideline).then(res => {
							this.finish("修改", res.code, res.msg)
						})
					} else {
						this.guideline.spotId = this.spotId;
						this.guideline.comboId = this.comboId;
						addGuideline(this.guideline).then(res => {
							this.finish("新增", res.code, res.msg)
						})
					}
				// }).catch(errors => {
				// 	uni.$u.toast('请正确填写信息!')
				// })
			},

			finish(txt, code, msg) {
				if (code != 200) {
					this.$u.toast(msg);
					return
				}

				this.$u.toast(txt + "成功!");
				this.redirectPage(this.redirect);
			},

			resetForm() {
				this.guideline = {
					guidelineId: null,
					userId: null,
					spotId: null,
					comboId: null,
					guidelineTitle: null,
					guidelineContent: null,
					pictures: null,
					createTime: null
				};
			},

			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			//请求到后端上传图片
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: process.env.BASE_APP_URL + '/upload/spotPictures',
						filePath: url,
						header: {
							"Content-Type": "multipart/form-data",
							"Authorization": uni.getStorageSync('token')
						},
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(JSON.parse(res.data).url)
							}, 1000)
						}
					});
				})
			},

			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			}
		},
	};
</script>

<style>
	page {
		height: 100%;
		background: white;
	}

	.box {
		margin: 10px 20px 20px 20px;
	}

	.confirmButton {
		padding-bottom: 50px;
	}

	.u-form-item__body__left.data-v-5e7216f1 {
		position: relative;
	}

	.u-form-item__body__left__content.data-v-5e7216f1 {
		position: absolute;
		top: 0;
	}
</style>

3、java代码,oss处理代码参考文章java调用对象存储OSS-优快云博客

package com.ruoyi.oss;  
  
import com.ruoyi.common.core.domain.AjaxResult;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.PostMapping;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RestController;  
import org.springframework.web.multipart.MultipartFile;  
  
@RestController  
@RequestMapping("/mobile/upload")  
public class UploadController {  
	@Autowired  
	private UploadService uploadService;  
	  
	@Autowired  
	private StorageOss storageOss;  
	  
	@PostMapping("/spotPictures")  
	public AjaxResult uploadSpotPictures(MultipartFile file) {  
		return uploadService.upload(file,storageOss.getSoptPath());  
	}  
}

### uView-UI Framework Form 表单使用教程 #### 创建基础表单 在 `uView` 中创建一个简单的表单,可以利用 `<u-form>` 组件来实现。此组件允许开发者定义一组输入控件,并提供验证功能。 ```html <template> <view> <!-- 定义表单--> <u-form :model="form" ref="uForm"> <u-form-item label="用户名" prop="username"> <u-input v-model="form.username"></u-input> </u-form-item> <u-form-item label="密码" prop="password"> <u-input type="password" v-model="form.password"></u-input> </u-form-item> <button @click="submit">提交</button> </u-form> </view> </template> <script> export default { data() { return { form: { username: '', password: '' } }; }, methods: { submit() { this.$refs.uForm.validate((valid) => { if (valid) { console.log('提交成功', this.form); } else { console.error('校验失败'); } }); } } }; </script> ``` 上述代码展示了如何构建并初始化带有两个字段(用户名和密码)的基础表单[^1]。 #### 添加验证规则 为了确保用户输入的数据有效,在 `u-form` 上设置验证规则是非常重要的。这可以通过给 `rules` 属性赋值完成: ```javascript data() { return { rules: { username: [ { required: true, message: '请输入用户名' }, { min: 3, max: 8, message: '长度应介于 3 到 8 字符之间'} ], password: [{ required: true, message: '请输入密码'}] }, // ...其他数据属性... }; }, mounted(){ this.$nextTick(() => { this.$refs.uForm.setRules(this.rules); }) } ``` 这段脚本设置了当页面加载完成后立即应用这些验证规则。 #### 处理复杂场景下的表单逻辑 对于更复杂的业务需求,比如动态添加/移除表单项、异步获取初始值等情况,则需进一步扩展表单处理方式。此时可借助 Vue 的生命周期钩子以及事件监听机制来进行操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值