简体   繁体   English

从表单获取文件而无需查询输入字段

[英]Get files from form without querying for input field

I'm trying to upload files using AJAX. 我正在尝试使用AJAX上传文件。 However, I'm having issues grabbing the files from my form. 但是,我在从表单中获取文件时遇到问题。 I want to gather all the 我想收集所有

<input type="file">

fields that are nested within the form, without using their specific ids. 嵌套在表单中的字段,而不使用其特定ID。 So, not like this: 因此, 不是这样的:

console.log($( "#i_dont_want_to_query_for_this_id" )[0].files);
//FileList {0: File, length: 1}

I feel there must a be way to get them from the form element itself: 我觉得必须有一种方法可以从form元素本身获取它们:

<form class="part-form">
  ...
  <input type="file" id="i_dont_want_to_query_for_this_id">
</form>

This is how I handle the submit: 这是我处理提交的方式:

$( ".part-form" ).each(function () {
        var $me = $( this );
        $me.on('submit', function (event) {
            event.preventDefault();
            var formElement = $me[0];
            var fd = new FormData(formElement);
            ...
 }

I guess this can also be achieved using classes and each() on these, but I feel there must be a way to grab all files in a submitted form by simply using the data in the form itself, I just cannot find it. 我想这也可以通过使用类和each()来实现,但是我觉得必须有一种方法可以通过简单地使用表单本身中的数据来获取提交表单中的所有文件,但我找不到它。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

You can use an attribute selector like $("file[type=input]") to get all the file inputs. 您可以使用$("file[type=input]")的属性选择器来获取所有文件输入。 Here's a fiddle . 这是一个小提琴

$(document).ready(function() {
    $( ".part-form" ).each(function () {
          var $me = $( this );
          $me.on('submit', function (event) {
              event.preventDefault();
              var $resultDiv = $("#result-div");
              $me.find("input[type=file]").each(function(index, fileInput) {
                  for(var i = 0; i < fileInput.files.length; i++) {
                      // Do whatever you really want to do with the file.
                      var $span = $("<span />");
                      $span.text(fileInput.files[i].name);
                      $resultDiv.append($span);
                  }
              })
          });
     });
})

Use can use selector $("input[type='file']") 使用可以使用选择器$(“ input [type ='file']”)

 $(document).on('change', 'input[type="file"]', function(){ console.log($(this)[0].files) alert($(this)[0].files) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="part-form"> ... <input type="file" id="i_dont_want_to_query_for_this_id"> <input type="file" id="i_dont_want_to_query_for_this_id2"> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM