jQuery从零开始上传多个文件


jQuery multiple file upload from scratch

我正试图使用新的HTML5multiple属性在jQuery中实现一个多图像上传器。

我的代码如下:

<form action="file-upload.php" method="post" enctype="multipart/form-data">
    <input name="userfiles" type="file" multiple="multiple">
</form>

我使用的JS代码取自这里关于SO的讨论,如下所示:

 $('input[name=userfiles]').change(function() {
    var names = [];
    for (var i = 0; i < $(this).get(0).files.length; ++i) {
        names.push($(this).get(0).files[i].name);
        console.log(names[i]);
    }
 });

有了这个,我可以在控制台上打印我选择的文件名,但如果我需要获得这些文件的确切值()呢?我尝试将.name替换为.val(),但出现错误。

如果我想用$.ajax处理它们,我想我需要每个文件的fakepath。如果这是正确的,我如何在发送get请求的PHP文件中循环遍历它们,以便上传它们?

您可以使用HTML5 FormData API。https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

var form = new FormData();
for (var i = 0; i < $(this).get(0).files.length; ++i) {
    form.append('userfiles[]', $(this).get(0).files[i]);
}
// send form data with ajax
$.ajax({
    url: 'url',
    type: "POST",
    data: form
});

或者,如果您不能使用FormData,有一种方法可以本地发送:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files

您不需要操作文件路径,在ajax调用中只需使用file并将其放入新的FormData 中

类似的东西:

 $.ajax({
'type':'POST',
'data': (new FormData()).append('file', $(this).get(0).files[i])

请参阅HTML5多文件上传:通过AJAX 逐个上传

如果你使用jquery文件上传插件,你可以使用这个

<input class="fileupload" type="file" name="file">

$('.fileupload').each(function () {
  $(this).fileupload({
  //your code goes here
})