jquery实现文件上传

编程知识 行业动态 更新时间:2024-06-13 00:21:04
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="./lib/jquery.js"></script>
		
		<title></title>
	</head>
	<body>
		
		<input type="file" id="file1" />
		<img src="layui/css/modules/layer/default/loading-0.gif" class="loading" style="display: none;"/>
		<img src="layui/css/modules/layer/default/loading-1.gif" class="loading" style="display: none;"/>
		<img src="layui/css/modules/layer/default/loading-2.gif" class="loading" style="display: none;" />
		<img src="./loading.gif" class="loading" style="display: none;"/>
		<button id="sendFile">上传文件</button>
		<script>
		$(function(){
			// 为发送文件按钮绑定单价事件,,判断是否上传了文件
			$('#sendFile').on('click',function(){
				// 【0】表示转换为原生的dom对象,使用files属性访问文件列表
				var files = $('#file1')[0].files
				if(files.length <=0 ){
					return alert('请选择文件后再上传!')
				}
				// console.log('ok')
				// 使用jQuery发起上传文件请求
				var fd = new FormData()
				fd.append('avatar',files[0])
				$.ajax({
					type:'post',
					url:'http://www.liulongbin.top:3006/api/upload/avatar',
					data:fd,
					processData:false,
					contentType:false,
					success:function(res){
						console.log(res)
					}
				})
			})
			//点击上传文件后加载图片显示
			$(document).ajaxStart(function(){
				$('.loading').show()
			})
			// 文件上传完成后加载图片消失
			$(document).ajaxStop(function(){
				$('.loading').hide()
			})
		})
		</script>
	</body>
</html>

结果

 

 

 

更多推荐

jquery实现文件上传

本文发布于:2023-03-31 02:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/d3d41d707ee136dd2163c182585cc32e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件上传   jquery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!