jQuery 从头开始​​上传多个文件

jQuery multiple file upload from scratch

我正在尝试使用新的 HTML5 multiple 属性在 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]);
    }
 });

这样我就可以在控制台上打印文件名 select,但是如果我需要获取这些文件的确切 val() 怎么办?我尝试用 .val() 替换 .name,但出现错误。

我想我需要每个文件的 fakepath 如果我想能够使用它们 $.ajax。如果这是正确的,我如何在发送 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 调用中只需使用文件并将其放入新的 FormData

类似的东西:

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

参见 HTML5 multiple file upload: upload one by one through AJAX

如果你使用 jquery-file-upload 插件你可以使用这个

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

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