Vue+Ajax+PHP实现文件上传

2022-07-28,,,

1、HTML代码
<input type="file" @change="upload($event)"/>
<button @click="add()">提交</button>
2、JavaScript代码
<script type="text/javascript" src="js/vue.min.js"></script>
<script type="text/javascript">
	var vm = new Vue({
		el: "#app",
		data: {
			image: ""
		},
		methods: {
			upload: function (event) {
				vm.image = event.target.files[0];
			},
			add: function () {
				let formData = new FormData();
				formData.append('image', this.image);
				$.ajax({
					url: "add.php",
					type: "POST",
					data: formData,
					processData: false,
					async: false,
					contentType: false,
					success: function (res) {
						console.log(res);
					}
				})
			}
		}
	})
</script>
3、PHP(add.php)代码
<?php
$image = $_FILES['image'];
// 取出后缀名
$ext = strtolower(substr(strrchr($image['name'],'.'),1));
// 新命名
$imageName = time().uniqid().'.'.$ext;
// 保存路径
$savePath = "uploads/".$imageName;
$info = move_uploaded_file($image['tmp_name'], $savePath);
print_r($info);
exit;

本文地址:https://blog.csdn.net/ZhangJiWei_2019/article/details/109616045

《Vue+Ajax+PHP实现文件上传.doc》

下载本文的Word格式文档,以方便收藏与打印。