简体   繁体   中英

Image not uploading without submit button

I am trying to upload mp3 file to server without using submit button i am using ajax but file not uploading to server.Where i am wrong here is my code

<script>
$(document).ready(function() {
    $('#fileToUpload').change(function(){
        var file_data = $('#fileToUpload').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', file_data);
        $.ajax({
            url: "modules/phone/newvoicemail.php",
            type: "POST",
            data: form_data,
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                console.log(data);
            }
        });
    });
});
</script>

In newvoicemail.php i put following code

$src = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['fileToUpload']['name'];
    $file_size =$_FILES['fileToUpload']['size'];
    $file_tmp =$_FILES['fileToUpload']['tmp_name'];
    $file_type=$_FILES['fileToUpload']['type'];
    move_uploaded_file($file_tmp,"voicemail/".$file_name);

here is my html code

<form name="voicemailform" action="modules/phone/voicemail.php" method="POST" enctype="multipart/form-data" class="form-inline for-frm">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
  1. Since you are uploading using ajax, you do not need name , action , method and enctype attributes on your HTML form tag. Same applies to name attribute of file input tag.

  2. You need to add enctype: 'multipart/form-data', to $.ajax({...});

  3. Since you are appending form data with param name file in JS as form_data.append('file', file_data); , you should access it in php as $_FILES['file'] and not $_FILES['fileToUpload']

HTML Code:

<form class="form-inline for-frm">
    <input type="file" id="fileToUpload">
</form>

JS Code:

       $('#fileToUpload').change(function () {
            var file_data = $('#fileToUpload').prop('files')[0];
            var form_data = new FormData();
            form_data.append('file', file_data);
            $.ajax({
                url: "modules/phone/newvoicemail.php",
                type: "POST",
                data: form_data,
                contentType: false,
                cache: false,
                enctype: 'multipart/form-data',
                processData: false,
                success: function (data) {
                    console.log(data);
                }
            });
        });

PHP Code: newvoicemail.php

<?php
    $src = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['file']['name'];
    move_uploaded_file($src, "./voicemail/".$file_name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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