With HTML5 you can make file uploads with Ajax and jQuery.
(使用HTML5,您可以使用Ajax和jQuery进行文件上传。)
Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). (不仅如此,您还可以执行文件验证(名称,大小和MIME类型)或使用HTML5进度标签(或div)处理进度事件。)
Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution. (最近,我不得不制作一个文件上传器,但是我不想使用Flash ,iframe或插件,经过一番研究后,我提出了解决方案。)
The HTML:
(HTML:)
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want.
(首先,您可以根据需要进行一些验证。)
For example, in the .on('change')
event of the file: (例如,在文件的.on('change')
事件中:)
$(':file').on('change', function () {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k');
}
// Also see .name, .type
});
Now the $.ajax()
submit with the button's click:
(现在,单击按钮即可提交$.ajax()
:)
$(':button').on('click', function () {
$.ajax({
// Your server script 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 XMLHttpRequest
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;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy.
(如您所见,借助HTML5(和一些研究),文件上传不仅成为可能,而且超级容易。)
Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser. (请尝试使用Google Chrome浏览器,因为示例的某些HTML5组件并非在每种浏览器中都可用。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…