我有一个多文件上传表单:
<input type="file" name="files" multiple />
我用ajax发布这些文件。我想逐个上传所选的文件(创建单独的进度条,并且出于好奇心)。
我可以通过
获取文件列表或单个文件FL = form.find('[type="file"]')[0].files
F = form.find('[type="file"]')[0].files[0]
yieling
FileList { 0=File, 1=File, length=2 }
File { size=177676, type="image/jpeg", name="img.jpg", more...}
但FileList是不可变的,我无法弄清楚如何提交单个文件。
我认为这是可能的,因为我看到http://blueimp.github.com/jQuery-File-Upload/。我不想使用这个插件,因为它与学习结果一样多(而且无论如何都需要太多的custimizing)。我也不想使用Flash。
答案 0 :(得分:30)
要使其成为同步操作,您需要在完成最后一次操作时启动新传输。例如,Gmail会同时发送所有内容。
有关AJAX文件上载进度的事件在原始progress
实例上为onprogress
或XmlHttpRequest
。
因此,在每个$.ajax()
之后,在服务器端(我不知道你将要使用的是什么),发送一个JSON响应以在下一个输入上执行AJAX。一个选项是将AJAX元素绑定到每个元素,以便更容易,所以你可以在success
$(this).sibling('input').execute_ajax()
中进行操作。
这样的事情:
$('input[type="file"]').on('ajax', function(){
var $this = $(this);
$.ajax({
'type':'POST',
'data': (new FormData()).append('file', this.files[0]),
'contentType': false,
'processData': false,
'xhr': function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', progressbar, false);
}
return xhr;
},
'success': function(){
$this.siblings('input[type="file"]:eq(0)').trigger('ajax');
$this.remove(); // remove the field so the next call won't resend the same field
}
});
}).trigger('ajax'); // Execute only the first input[multiple] AJAX, we aren't using $.each
以上代码适用于多个<input type="file">
但不适用于<input type="file" multiple>
,在这种情况下,它应该是:
var count = 0;
$('input[type="file"]').on('ajax', function(){
var $this = $(this);
if (typeof this.files[count] === 'undefined') { return false; }
$.ajax({
'type':'POST',
'data': (new FormData()).append('file', this.files[count]),
'contentType': false,
'processData': false,
'xhr': function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', progressbar, false);
}
return xhr;
},
'success': function(){
count++;
$this.trigger('ajax');
}
});
}).trigger('ajax'); // Execute only the first input[multiple] AJAX, we aren't using $.each
答案 1 :(得分:8)
This looks like a very good tutorial, just what you're looking for
注意,并非所有浏览器都支持通过vanilla ajax上传,我仍然建议使用iframe
。 (I.E动态创建iframe并使用javascript发布它)
I have always been using this script我发现它非常简洁。如果您想通过创建iframe了解如何上传,您应该深入了解它的来源。
希望有所帮助:)
额外修改
要使用iframe方法创建进度条,您需要在服务器端执行一些工作。如果你使用的是php,你可以使用:
如果使用nginx,您也可以选择使用Upload progress module
进行编译所有这些都以相同的方式工作 - 每次上传都有一个UID,您将通过ajax以一致的间隔请求与该ID相关联的“进度”。这将返回服务器确定的上传进度。
答案 2 :(得分:4)
我遇到了同样的问题,并提出了这个解决方案。我只是使用multipart检索表单,并在递归调用(文件后文件)中启动ajax请求,只在完成时调用next。
var form = document.getElementById( "uploadForm" );
var fileSelect = document.getElementById( "photos" );
var uploadDiv = document.getElementById( "uploads" );
form.onsubmit = function( event ) {
event.preventDefault( );
var files = fileSelect.files;
handleFile( files, 0 );
};
function handleFile( files, index ) {
if( files.length > index ) {
var formData = new FormData( );
var request = new XMLHttpRequest( );
formData.append( 'photo', files[ index ] );
formData.append( 'serial', index );
formData.append( 'upload_submit', true );
request.open( 'POST', 'scripts/upload_script.php', true );
request.onload = function( ) {
if ( request.status === 200 ) {
console.log( "Uploaded" );
uploadDiv.innerHTML += files[ index ].name + "<br>";
handleFile( files, ++index );
} else {
console.log( "Error" );
}
};
request.send( formData );
}
}
答案 3 :(得分:0)
使用此源代码,您可以通过以下方式上传多个文件,例如Google 一个通过ajax。您还可以看到上传进度
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
JavaScript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
}
})
.success(function(res,status) {
if(status == 'success'){
percent = 0;
$('#prog'+cl).text('');
$('#prog'+cl).text('--Success: ');
if(cl < ttl){
uploadajax(ttl,cl+1);
}else{
alert('Done ');
}
}
})
.fail(function(res) {
alert('Failed');
});
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
答案 4 :(得分:0)
HTML代码
<div class="row">
<form id="singleUploadForm" name="singleUploadForm" style="float: right; padding-right: 25px">
<input style="float: left;" id="singleFileUploadInput" type="file" name="files" class="file-input btn btn-default" required multiple/>
<button style="float: left" type="submit" class="btn .btn-primary">Upload</button>
</form>
</div>
JavaScript代码
$('#mutipleUploadForm').submit(function (event) {
var formElement = this;
var formData = new FormData(formElement);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/uploadFile",
data: formData,
processData: false,
contentType: false,
success: function (response) {
alert("Image Uploaded Successfully");
location.reload();
},
error: function (error) {
console.log(error);
// process error
}
});
event.preventDefault();
});
Spring Controller Class
@PostMapping("/uploadFile")
@ResponseBody
public boolean uploadMutipleFiles(@RequestParam("file") MultipartFile[] file) {
List<Boolean> uploadStatusList = new ArrayList<>();
for (MultipartFile f : file) {
uploadStatusList.add(uploadFile(f));
}
return !uploadStatusList.contains(false);
}
public boolean uploadFile(@RequestParam("file") MultipartFile file) {
boolean uploadStatus = galleryService.storeFile(file);
return uploadStatus;
}
春季服务班
public boolean storeFile(MultipartFile file) {
boolean uploadStatus = false;
try {
String fileName = file.getOriginalFilename();
InputStream is = file.getInputStream();
Files.copy(is, Paths.get(imagesDirectory + fileName), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File store success");
uploadStatus = true;
} catch (Exception e) {
e.printStackTrace();
}
return uploadStatus;
}