H5 使用Ajax上传文件 提交FormData对象

简单的 ,前端代码如下

<div class="container"> 
	<div class="form-horizontal">
		<div class="form-group">
			<label class="col-md-2 control-label">名称</label>
			<div class="col-md-10">
				<input type="text" name="name" class="form-control">
			</div>
		</div>
		<div class="form-group">
			<label class="col-md-2 control-label">头像</label>
			<div class="col-md-10">
				<input type="file" name="file" class="form-control">
			</div>
		</div>
		<div class="form-group">
			<div class="col-md-10 col-md-offset-2">
				<button class="btn btn-default" id="sure">确定提交</button>
			</div>
		</div>
	</div>
</div>

一个input 一个file 一个button (代码看上去很多, 因为用了bootstrap)
下面是js

<script>
	$('#sure').click(function(e){
		//e.preventDefault();//阻止默认行为
		var oForm = new FormData();// 创建FormData 对象 调用append()方法来添加字段
		var file = $('#portrait')[0].files[0];//上传文件 file

		oForm.append('name' ,$('#name').val());//
		if( typeof file != 'undefined' )
			oForm.append('portrait' ,file);

		$.ajax({
			url : '/index/index/userPost' ,//后台文件
			type: 'post',
			data: oForm,
			processData: false,  // 不处理数据
			contentType: false,   // 不设置内容类型
			success:function(re)
			{
				//code..
			}
		});
	})
</script>

就这样, 在后台文件中通过 $_FILES 可以处理要上传的文件
附一个文件上传类:
https://blog.youkuaiyun.com/csdn_zhongwu/article/details/84308186

更多 FormData 的使用请参阅文档:
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值