The first two days of the project need to use asynchronous upload pictures and display upload progress function, so find a lot of foreign articles, over the mountains to meet all kinds of pits, here to write an article recorded.
Html
There is nothing to say about the HTML code, a form forms, and file type input. Let's look at the JS section.
Javascript
Bind the ' Submit ' event.
$ (' #fileupload-form '). On (' Submit ', (function (e) {e.preventdefault ();
Serialized form 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, befores Ubmit:function () {//Upload image before processing}, Uploadprogress:function (event, Positio
N, total, percentcomplete) {//Here Control progress bar}, Success:function () {},
Error:function (data) {alert (' Upload image error ');
}
});
}));
Binding file Selection event, a Select the picture, let ' form ' submit.
$ (#fileupload). On (change, function () { $ (this). Parent (). submit (); });
Php
遇到的坑:
序列化表单,因为是文件,不能通过val()
,text()
等方法获取到它的值,只能通过序列化表单提交。代码里面使用.serialize()
,有另外一种做法是使用.FormData()
来提交,但是实验过程中,一开始正常,后来报错了。在stackoverflow.com上有人看到有人遇到同样地问题,没有解决,于是就放弃了。 普通的ajax
是没办法或者说很难拿到上传进度的。这里使用了一个插件jQuery Form Plugin,使用方法很简单,原本ajax
的配置都能用,而且有很多实用功能和详尽的使用文档。推荐~ ajax
上传图片这三个参数必须配置contentType: false, cache: false, processData:false,
。 获取本地预览图,这种方法可能会有浏览器兼容性问题。
$(#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]); } }
php部分注意虽然Ajax那里使用的是POST
方法,但是后台接受的时候只要是文件都是用$_FILES
。你可以通过$_FILES['file']['type']
去判断文件格式来做安全处理,我们这里只是演示。还有其他参数,比如tmp_name
是文件路径,name
是文件名。后台接收以后,你可以使用move_uploaded_file()
来将文件保存到服务器上。这里就不多说。
其他补充
另外@_w同学补充,不刷新页面还可以通过设置form
的target
属性指向一个当前页面隐藏的iframe
来实现。让那个iframe
去刷新跳转页面。上面提到的jQuery Form Plugin也支持你这么做。
另外再推荐一个插件jquery-iframe-transport
recommended reading
hljs= Uploading-files-with-ajax image-upload-example jquery-progress-bar-for-php-ajax-file-upload
JavaScript
, and hopefully this article will help more people with the same problems. If the writing is not good or wrong, I also hope that colleagues can kindly point out.