Ruoyi 모바일 단말기 Ruoyi-App - uview2.0을 사용하여 사진 업로드 또는 휴대폰 앨범에서 업로드를 개발하고 실제 머신 디버깅을 수행합니다.

이 기사는 uView2의 업로드 구성 요소를 사용하여 휴대폰 앨범에서 업로드하고 사진을 업로드할 수도 있습니다. 이 구성 요소는 미니 프로그램, h5 및 사용하기 쉬운 앱 측에 사진을 업로드할 수 있습니다.

1. 프론트엔드 코드

<template>
	<view class="u-page">
		<view class="u-demo-block">
			<view class="u-demo-block__content">
				<!-- 注意,如果需要兼容微信小程序,最好通过setRules方法设置rules规则 -->
				<u--form
					labelPosition="left"
					:model="form"
					ref="form1"
				>		
            <u-form-item
				label="上传照片"
				prop="form.problemPhotos"
				borderBottom
				labelWidth="80"
				ref="item3"
			>
				<u-upload
					:fileList="fileList1"
					:previewFullImage="true"
					@afterRead="afterRead"
					@delete="deletePic"
					name="1"
					multiple
					:maxCount="10"
				></u-upload>
			</u-form-item>
		</u--form>
				<u-button
					type="primary"
					text="提交"
					customStyle="margin-top: 50px"
					@click="submit"
				></u-button>
            </view>
		</view>
	</view>
</template>

2. 사진 읽기 또는 사진 업로드

uView 2.0 - nvue의 uni-app 생태 프레임 워크와 완벽하게 호환 - uni-app UI 프레임워크

(1) 파일을 업로드하고 URL을 자신의 배경 경로로 작성하고 헤더는 Ruoyi의 컴퓨터 작성 방법을 참조하십시오.

     uni.uploadFile({                 url: '/dev-api/common/upload',                  header: {                         Authorization: "Bearer " + getToken(),                       },                 filePath: url,                 name: 'file',





(2) uploadFilePromise 함수의 반환 값 resolve(JSON.parse(res.data).fileName)를 통해 fileList 배열 객체의 rl에 파일 경로 /profile/upload/2023/02/27/123_20230227141005A061.jpg를 할당합니다.

(3) 그런 다음 배열을 문자열로 변환하고 제출할 때 ','로 구분된 this.form.problemPhotos에 할당합니다.

                      let images = []    
                        this.fileList1.forEach((item) => {                                      images.push(item.rl)                                  })                          this.form.problemPhotos=images.join(',');


구체적인 코드는 다음과 같습니다.

import { getToken } from "@/utils/auth";
<script>
	export default {
		data() {
			return {
				fileList1: [],
			}
		},
		methods: {
		// 删除图片
			deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1)
			},
						// 新增图片
			async afterRead(event) {
				
				// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
				let lists = [].concat(event.file)		
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
				this[`fileList${event.name}`].push({
				...item,
				status: 'uploading',
				message: '上传中'
				})
				})
				console.log(this.fileList1)
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)		
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					rl: result
					}))
					fileListLen++
					}

				console.log(this.fileList1);
				//this.problemPhotos=this.fileList1;
			},
		    uploadFilePromise(url) {
	            let _self=this;
		    	return new Promise((resolve, reject) => {
		    	let a = uni.uploadFile({
		    	url: '/dev-api/common/upload', 
				header: {
				        Authorization: "Bearer " + getToken(),
				      },
		    	filePath: url,
		    	name: 'file',
		    	success: (res) => {
					 let result = JSON.parse(res.data)
				   //	console.log(result.fileName);
		    		setTimeout(() => {				   
		    		resolve(JSON.parse(res.data).fileName)
		    		}, 1000)
		    	}
		    	});
		    	})
		    },
			submit() {
					 if (this.form.id == null) {
						 this.form.problemStatus=1;
						let images = []	
						this.fileList1.forEach((item) => {
						 			images.push(item.rl)
						 		})
						 this.form.problemPhotos=images.join(',');
					     addProblems(this.form).then(response => {
					     this.$modal.msgSuccess("新增成功");
					});
					}
			}
		},
	}
</script>

4. 다음과 같이 manifest.json을 구성하고 실제 머신 디버깅을 위한 대상을 구성합니다: http://127.0.0.1:8085 . 여기서 8085는 백엔드 포트 번호입니다.

 "h5" : {
        "template" : "static/index.html",
        "devServer" : {
            "port" : 9092,
            "https" : false,
            "disableHostCheck" : true, //设置跳过host检查
            "proxy" : {
                "/dev-api" : {
                    "target" : "http://127.0.0.1:8085", //目标接口域名
                    "changeOrigin" : true, //是否跨域
                    "secure" : false, // 设置支持https协议的代理
                    "pathRewrite" : {
                        "^/dev-api" : ""
                    }
                },
                "/prod-api" : {
                    "target" : "http://127.0.0.1:8085", //目标接口域名
                    "changeOrigin" : true, //是否跨域
                    "secure" : false, // 设置支持https协议的代理
                    "pathRewrite" : {
                        "^/prod-api" : ""
                    }
                }
            }
        },

5. WeChat 도구의 실제 장치 디버깅을 사용하여 휴대폰에서 작은 프로그램 형태로 "사진" 또는 "휴대폰 앨범에서 선택"을 선택할 수 있습니다.

6. 브라우저에서 h5를 사용했을 때의 효과는 다음과 같습니다.

추천

출처blog.csdn.net/zhaolulu916/article/details/127978862