使用Ajax异步上传图片的方法(html,javascript,php)
发布时间:2020-12-16 01:56:15 所属栏目:百科 来源:网络整理
导读:前两天项目中需要用到异步上传图片和显示上传进度的功能,于是找了很多外国的文章,翻山越岭地去遇上各种坑,这里写篇文章记录一下。 HTML form id = "fileupload-form" input id = "fileupload" type = "file" name = "file" / form HTML代码没什么好说,一
前两天项目中需要用到异步上传图片和显示上传进度的功能,于是找了很多外国的文章,翻山越岭地去遇上各种坑,这里写篇文章记录一下。 HTML<form id="fileupload-form">
<input id="fileupload" type="file" name="file" >
</form>
HTML代码没什么好说,一个form表单,还有文件类型的input。我们来看js部分。 javascript//绑定了`submit`事件。
$('#fileupload-form').on('submit',(function(e) {
e.preventDefault();
//序列化表单
var serializeData = $(this).serialize();
// var formData = new FormData(this);
$(this).ajaxSubmit({
type:'POST',url: *yoururl*,dataType: 'json',data: serializeData,// data: formData,
//attention!!!
contentType: false,cache: false,processData:false,beforeSubmit: function() {
//上传图片之前的处理
},uploadProgress: function (event,position,total,percentComplete){
//在这里控制进度条
},success:function(){
},error:function(data){
alert('上传图片出错');
}
});
}));
//绑定文件选择事件,一选择了图片,就让`form`提交。
$("#fileupload").on("change",function() {
$(this).parent().submit();
});
PHP<?php
//通过$_FILES[]去获取文件
echo '$_FILES['file']';
遇到的坑:
$("#fileupload").change(function(){
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#theImg').attr('src',e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
}
其他补充另外@_w同学补充,不刷新页面还可以通过设置 推荐阅读
如需转载,请注明出处:http://www.w3ctrain.com/2015/07/11/uploading-image-with-ajax/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |