我有一个工作的文件上传表单,使用XMLHttpRequest 2将文件上传到Transloadit(一个文件处理服务)。进度事件在Firefox和Chrome中正确触发,包括桌面版和Android版。但是,Android (4.0)原生浏览器不会触发这些事件,因此我的进度条对于我网站的这些用户无效。由于自从3.0版本起,Android应该支持XHR2和ProgressEvent,所以我不知道发生了什么事情。
代码如下:
代码如下:
<!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>