Image not uploading without submit button

前端 未结 1 345
礼貌的吻别
礼貌的吻别 2021-01-27 08:02

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



        
相关标签:
1条回答
  • 2021-01-27 08:15
    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);
    
    0 讨论(0)
提交回复
热议问题