문제

I've this code in JS i am sending an XHR post request to the php file how to handle getting the file and the string in PHP?

I am gonna use the string to create a path like "Code/Math" then move file to that path.

JavaScript

$( document ).ready(function() {
    $('#Upload').click(function(){
        var formData = new FormData();
        var url = 'uploadFile.php';
        var file = $("#file");
        var xhr = new XMLHttpRequest();
        formData.append('File',file[0].files[0]);
        formData.append('Path','/Upload/Upload');
        xhr.addEventListener('progress', function (e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            var percent = (Math.floor(done / total * 1000) / 10) + '%';
            $('#uploadprogress').css('width', percent+'%');
        }, false);

        if (xhr.upload) {
            xhr.upload.onprogress = function (e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                var percent = (Math.floor(done / total * 1000) / 10) + '%';
            };
        }

        xhr.onreadystatechange = function (e) {
            if (4 == this.readyState) {
                $('#message').text(e.currentTarget.response);
                $('#uploadprogress').css('width', '0%');
                $('#file').val('');
            }
        };

        xhr.open('post', url, true);
        xhr.send(formData);
    });

    var progressHandling = function(e){
        if(e.lengthComputable){
            var percent = Math.round((e.loaded / e.total) * 100);
            $('#uploadprogress').css('width', percent+'%');
        }
    };

    var completeHandler = function(data){
        $('#message').text(data);
        $('#uploadprogress').css('width', '0%');
        $('#file').val('');
    };
});
도움이 되었습니까?

해결책

When handling ajax requests on the server, think of the ajax as nothing more than a form submit. You handle it exactly the same way as if it were a form. For a POST request, the parameters will be available in $_POST, $_GET for get requests, and files will be under $_FILES. there are exceptions though depending on how exactly the ajax request was formed/sent, because it is possible to post data in the request body rather than as parameters, however that doesn't really apply to your case.

TL;DR:

use $_POST["Path"] and $_FILES["File"]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top