最近我不得实现一个文件异步上传的功能,但是我不想使用Flash或 或者插件,经过一些研究,我想出了这个解决方案。于是分享给大家:
HTML:
<form enctype=\"multipart/form-data\">
<input name=\"file\" type=\"file\" />
<input type=\"button\" value=\"Upload\" />
</form>
<progress></progress>
首先,您可以根据需要进行一些验证。例如,在文件的 事件中:
$(\':file\').on(\'change\', function() {
var file = this.files[0];
if (file.size > 1024) {
alert(\'max upload size is 1k\')
}
// Also see .name, .type
});
点击按钮并实现AJAX异步上传文件:
$(\':button\').on(\'click\', function() {
$.ajax({
// Your server to process the upload
url: \'upload.php\',
type: \'POST\',
// Form data
data: new FormData($(\'form\')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom HttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener(\'progress\', function(e) {
if (e.lengthComputable) {
$(\'progress\').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
从上面代码你可以看到,HTML5文件上传不仅变得可能而且非常简单。
继续阅读与本文标签相同的文章
-
未来十年,最为吃香的4个大学专业,毕业后就是香饽饽!
2026-05-14栏目: 教程
-
还不会制作填充地图,试试这种方法,2分钟搞定,让你秒变大神
2026-05-14栏目: 教程
-
顺丰自研机器人惊艳亮相,化身“快递小哥”亮绝活,盯上万亿市场
2026-05-14栏目: 教程
-
女生“主动”与你分享这3个秘密?520%偷偷喜欢你,臭弟弟冲鸭
2026-05-14栏目: 教程
-
这4类大学专业很吃香,市场人才紧缺,毕业后前景很好!
2026-05-14栏目: 教程
