使用ajax完成图片上传

小董大咖 · 收录于 2023-09-24 03:58:02 · source URL

如何用ajax上传图片文件1:先说我们平时接触到的接口都是后台需要你给他传递几个参数,你就把参数对应的值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
     <script src="jquery-3.6.0.min.js"></script>    
</head>
 
<style>
	.imge img{
		width: 150px;
		height: 80px;
		margin-top: 70px;
		margin-left: 80px;
	}
</style>
 
 
<body>
	<form id="forms"  >
		<label>上传图片:<input type="file" id="file" name="file"></label>
		
		<input type="button" value="上传" id="sub">
	</form>
	<div class="imge"></div>
 
    <script>
 
let sub=document.getElementById('sub');
sub.onclick=function(){
	var form = new FormData(document.getElementById('forms'));
		console.log(form);
		$.ajax({
			url: "",
			type: 'POST',
			data: form,
			processData: false,
			contentType: false,
			success: function(data) {
			console.log(data);
			document.getElementsByClassName('imge')[0].innerHTML = data;
			},
		});
}
 
 
        </script>
</body>
</html>