js之图片上传

话不多说,直接上干货,注释在代码里面

下面是效果图和代码

html 复制代码
<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>Document</title>
		<style>
			/* form 表单定位 */
			.form-upload {
				width: 200px;
				height: 200px;
				border: 1px solid red;
				margin: 200px auto;
				position: relative;
			}

			/* 相对于form 表单定位 设置提醒文字 位于 第五层 */
			.form-upload-text {
				position: absolute;
				z-index: 5;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
			}

			/* 相对于 form 表单定位 设置 点击范围位于最上层 第十层 */
			.form-upload-file {
				position: absolute;
				z-index: 10;
				width: 200px;
				height: 200px;
				background-color: orange;
				opacity: 0;
			}

			/* 相对于 form 表单 定位设置 位于 文字 与 文件中间展示 第八层 */
			.form-upload-imgs {
				position: absolute;
				z-index: 8;
				width: 200px;
				height: 200px;
			}
		</style>
	</head>
	<body>
		<form class="form-upload" id="formUpload" action="" method="post" enctype="multipart/form-data">
			<span class="form-upload-text" id="submitButton">上传图片</span>
			<input type="file" class="form-upload-file" name="image" size="50" onchange="fileChange(this)">
			<img src="" class="form-upload-imgs" alt="">
		</form>
		<script>
			var imgUrl = ''

			function fileChange(target) {
				// 点击 input 的时候
				if (target.tagName === 'INPUT') {
					// 获取 form 表单的 第一个元素
					var formData = new FormData($('#formUpload')[0])
					// 发送 ajax 
					$.ajax({
						// 类型
						type: "POST",
						// url  地址
						url: "xxxxxxx",
						// 表单数据
						data: formData,
						// 是否异步
						// async: false,
						// 请求头设置
						contentType: false,
						// processData 默认为true,当设置为true的时候,jquery ajax 提交的时候不会序列化 data,而是直接使用data
						// 默认情况下会将发送的数据序列化以适应默认的内容类型application/x-www-form-urlencoded
						// 如果想发送不想转换的的信息的时候需要手动将其设置为false
						processData: false,
						// 成功的回调
						success: function(res) {
							console.log('图片 ----》 ', res)
							// 这里是 上传成功后 后台会返回 一个图片的绝对路径
							imgUrl = res.data.imgUrl
							// 找到 img 标签设置它的 图片路径
							$('.form-upload-imgs').attr('src', imgUrl)
						},
						// 失败的回调
						error: function(returndata) {
							console.log(returndata);
						}
					})
				}

			}
		</script>
	</body>
</html>

谢谢大家观看,我是小辉,请大家多多关照

相关推荐
工业甲酰苯胺3 小时前
TypeScript枚举类型应用:前后端状态码映射的最简方案
javascript·typescript·状态模式
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian4 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼4 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上4 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang4 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc4 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇5 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀5 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
liulilittle5 小时前
.NET ExpandoObject 技术原理解析
开发语言·网络·windows·c#·.net·net·动态编程