VUE+SpringBoot实现文件异步上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w_t_y_y/article/details/82253322
@RequestMapping("/upload")
	@ResponseBody
	public void upload(@RequestParam("file")MultipartFile  file[]){
		MultipartFile multipartFile = file[0];
		System.out.println("文件名称"+multipartFile.getOriginalFilename());
	}
<template>
	<div>
		<form>
			<input type="text" value="" v-model="name" placeholder="请输入用户名">
			<input type="text" value="" v-model="age" placeholder="请输入年龄">
			<input type="file" @change="getFile($event)">
			<button @click="submitForm($event)">提交</button>
		</form>

	</div>
</template>

<script>
	import axios from 'axios';
	axios.defaults.withCredentials = true;
	export default {
		data() {
			return {
				name: '',
				age: '',
				file: ''
			}

		},
		methods: {
			getFile(event) {
				this.file = event.target.files[0];
				console.log(this.file);
			},
			submitForm(event) {
				event.preventDefault();
				let formData = new FormData();
				formData.append('name', this.name);
				formData.append('age', this.age);
				formData.append('file', this.file);

				let config = {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				}

				axios.post('http://localhost:8082/user/upload', formData, config).then(function(response) {
					if(response.status === 200) {
						console.log(response.data);
					}
				})
			}
		}

	}
</script>

<style>

</style>

 把event去掉也对,即:

<template>
	<div>
		<form>
			<input type="text" value="" v-model="name" placeholder="请输入用户名">
			<input type="text" value="" v-model="age" placeholder="请输入年龄">
			<input type="file" @change="getFile()">
			<button @click="submitForm()">提交</button>
		</form>

	</div>
</template>

<script>
	import axios from 'axios';
	axios.defaults.withCredentials = true;
	export default {
		data() {
			return {
				name: '',
				age: '',
				file: ''
			}

		},
		methods: {
			getFile() {
				this.file = event.target.files[0];
				console.log(this.file);
			},
			submitForm() {
			//	event.preventDefault();
				let formData = new FormData();
				formData.append('name', this.name);
				formData.append('age', this.age);
				formData.append('file', this.file);

				let config = {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				}

				axios.post('http://localhost:8082/user/upload', formData, config).then(function(response) {
					if(response.status === 200) {
						
						console.log(response.data);
					}
				})
			}
		}

	}
</script>

<style>

</style>

猜你喜欢

转载自blog.csdn.net/w_t_y_y/article/details/82253322