如何通过javascript获取文件并发送给ajax

时间:2022-06-30 07:37:26

I have this form in html for multiple file uploading .

我有这个html格式的多文件上传。

<form class="userform" method="post" action="upload.php" role="form"   enctype="multipart/form-data" >
        <input  name="title" type="text" ><br/>
        <input  type="file" name="media[]" >
        <div class="filesupload">
          <input type="file" name="media[]" >
        </div>
<script>
 $(document).on("click",".add-new-file",function()
            {
                $('.filesupload').append('<input  name="media[]" type="file"  >');
            });
</script>
</form>

I will get input files by javascript and send to upload.php for uploading. but I don't know how to get files values in javascript.

我将通过javascript获取输入文件并发送到上载。php上传。但是我不知道如何在javascript中获取文件值。

1 个解决方案

#1


3  

If you using HTML5

如果你使用HTML5

   var fileList = document.getElementById("yourInput").files;
    for(var i = 0; i < fileList.length; i++) {
        //Do something with individual files
    }

Using jquery

使用jquery

$("input[name=file1]").change(function() {
    var names = [];
    for (var i = 0; i < $(this).get(0).files.length; ++i) {
        names.push($(this).get(0).files[i].name);
    }
    $("input[name=file]").val(names);
});​

#1


3  

If you using HTML5

如果你使用HTML5

   var fileList = document.getElementById("yourInput").files;
    for(var i = 0; i < fileList.length; i++) {
        //Do something with individual files
    }

Using jquery

使用jquery

$("input[name=file1]").change(function() {
    var names = [];
    for (var i = 0; i < $(this).get(0).files.length; ++i) {
        names.push($(this).get(0).files[i].name);
    }
    $("input[name=file]").val(names);
});​