natsuki_2002
natsuki_2002

Reputation: 25349

echo entire file in php and send to jquery

I'm using the JQuery Form Plugin to upload a file. I am able to send the contents of an uploaded txt file to the jquery associated with the form plugin but I want to send the entire file.

Right now I echo the variable $c in my php and this is sent to my jquery. Can I somehow send the entire file with $file?

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

foreach($_FILES as $file) {
    $n = $file['name'];
    $s = $file['size'];
$t = $file["tmp_name"];
$c= file_get_contents($t);


    if (is_array($n)) {
        $c = count($n);
        for ($i=0; $i < $c; $i++) {
            //echo "<br>uploaded: " . $n[$i] . " (" . $s[$i] . " bytes)";

        }
    }
    else {
        //echo "<br>uploaded: $n ($s bytes)";
    }
 //echo "<br>uploaded: $n ($s bytes)";
}

echo $c;

?>

Then in my jquery from the jquery form plugin:

$(document).ready(function() {

    (function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('#dataform').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal)
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal)
            percent.html(percentVal);
        },
        success: function(data, responseText, statusText, $form) {
            var percentVal = '100%';
            bar.width(percentVal)
            percent.html(percentVal);

            $.post('/submit', {name: data}, function(data) {
                $('body').append(data);
                });

        },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
    //
    }); 
    return false;
    })();       

});  

Upvotes: 0

Views: 102

Answers (2)

aorcsik
aorcsik

Reputation: 15552

Sending the contents of a file is equivalent to sending the file. The question is, why do you want to do what you are asking. If you want to spare the file handling on the server side, then I'm afraid this is just the way to do it.

Upvotes: 1

Labib Ismaiel
Labib Ismaiel

Reputation: 1340

you just have to keep one thing in mind, the ajax request will read the output sent by the server, that's why it reads only the echoed statement, just decide what you want to send and send it as plain text or whatever form you like, if you want to get the file, there might be a problem because the server will try to execute the content if it's a php file, but there is an easy hack, rename the extension of the file to something like txt and the server will send it as is, it's your decision to make.

Upvotes: 1

Related Questions