【发布时间】:2014-06-06 19:04:36
【问题描述】:
我有允许用户上传多个文件的上传表单。我决定如果文件很大,进度条会很好。下面是我的源代码。我是 jquery 的新手,通常我只会使用 php,但我发现 ajax 对用户更友好。
<div id="new_upload">
<div class="close_btn"></div>
<div id="uploads"></div>
<form action="global.func/file_upload.php" method="post" enctype="multipart/form-data" id="upload_file">
<fieldset><legend>Upload an image or video</legend>
<input type="file" id="file" name="file[]" placeholder="Upload Image or Video" multiple /><input type="submit" value="upload file" id="upload_file_btn" required />
</fieldset>
<div class="bar">
<div class="bar_fill" id="pb">
<div class="bar_fill_text" id="pt"></div>
</div>
</div>
</form>
</div>
<script>
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%') //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
function beforeSubmit(){
console.log('ajax start');
}
function afterSuccess(data){
console.log(data);
}
$(document).ready(function(e) {
$('#upload_file').submit(function(event){
event.preventDefault();
var filedata = document.getElementById("file");
formdata = new FormData();
var i = 0, len = filedata.files.length, file;
for (i; i < len; i++) {
file = filedata.files[i];
formdata.append("file[]", file);
}
formdata.append("json",true);
$.ajax({
url: "global.func/file_upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
dataType:"JSON",
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSubmit: beforeSubmit,
uploadProgress:OnProgress,
success: afterSuccess,
resetForm: true
});
});
});
</script>
图片上传工作正常,数组发送到 ajax 但进度条没有移动。事实上,调用需要产生这个的两个函数的console.log 也不会出现。有没有正确的方法来调用我的 ajax 请求中的函数,以使这个进度条工作。
beforeSubmit: beforeSubmit, 上传进度:OnProgress, 成功:afterSuccess,
请注意,当控制台显示我的数据时,此功能“成功:afterSuccess”正在工作。
【问题讨论】:
-
您为什么不检查 Eskinder 的回答?对我来说它似乎更完整。
标签: javascript jquery ajax file-upload jquery-file-upload