我有一个使用 XMLHttpRequest 2 将文件上传到 Transloadit(文件处理服务)的工作文件上传表单。进度事件在 Firefox 和 Chrome 中正确触发,无论是桌面版还是 Android 版。但是 Android (4.0) 股票浏览器不会触发这些事件,因此我的进度条不适用于我网站的那些用户。XHR2 和 ProgressEvent 据说从 3.0 开始在 Android 中得到支持,所以我不知道发生了什么。
代码是:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Upload test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link href="/assets/application.css" media="all" rel="stylesheet" type="text/css" /> <!-- twitter bootstrap -->
<script type="text/javascript">
var onprogress = function(e)
{
var $status = $('.status');
$status.text('onprogress: ' + (e.loaded / e.total) * 75 + '<br>');
if (e.lengthComputable) {
setProgress((e.loaded / e.total) * 75);
}
}
var setProgress = function(percent) {
percent = percent+'%';
var $progressBar = $('.progress .bar');
var $status = $('.status');
$progressBar.css('width', percent);
$progressBar.text(percent);
$status.text(percent);
};
var createAttachment = function(file) {
var params = {"blocking": true,"auth":{"key":"XXX"},"template_id":"XXX"}
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append('params', JSON.stringify(params));
data.append('attachment[file]', file);
var evtReceiver = xhr.upload || xhr;
evtReceiver.addEventListener('progress', onprogress, false);
xhr.onload = function(e) {
var resp = JSON.parse(e.target.response)
$('.image').append($('<img src="' + resp.results['android-thumb'][0].url + '">'))
setProgress(100);
};
xhr.open('POST', 'http://api2.transloadit.com/assemblies', true);
xhr.send(data);
};
$(document).ready(function() {
$('input[type=file]').on('change', function(event) {
createAttachment(event.target.files[0]);
});
});
</script>
</head>
<body>
<input type="file" name="my_file">
<div class="progress progress-striped active">
<div class="bar" style="width: 0;"></div>
</div>
<div class="status"></div>
<div class="image"></div>
</body>
</html>