0

is there any possible way to fetch the temporary file path of the file uploaded by

<input type="file"/>

and then send it to PHP via ajax and getting the file there and store it

explanation with the code will be helpful thankyou

Saurabh Gupta
  • 122
  • 2
  • 12
  • 1
    This doesn't make much sense. I can think of an approach, but it is stupidly complex and pointless. You seem to have a bad case of the [XY Problem](http://xyproblem.info/). What are you really trying to achieve? – Quentin Aug 13 '17 at 19:41
  • I want to send my form data with files uploaded to the server in a complete JSON format using Ajax but I don't wanna use javascript formdata object to achieve it – Saurabh Gupta Aug 13 '17 at 19:45
  • Then you need to read the file data. The path to the file is irrelevant. – Quentin Aug 13 '17 at 19:47
  • how can i read the file data can u please help me out with it – Saurabh Gupta Aug 13 '17 at 19:48

2 Answers2

0

There is no temporary file/path on client side which could be found via Javascript. You are sending the file (the binary data) with a HTTP request which will let the server create a temporary file.

Of course you could add the path in the response which is generated by the server/php. This can be done by getting the config upload_tmp_dir or calling sys_get_temp_dir.

You can find a more detailed answer here: How do I get the PHP Uploads directory?

Nils Rückmann
  • 593
  • 3
  • 16
0

(edited to not use FormData, although I highly recommend doing that over this)

javascript:

first a base64 file encoding function:

function getBase64(file, callback) {
   var reader = new FileReader();
   reader.readAsDataURL(file[0].files[0])
   reader.onload = () => {
       callback(reader.result);
   };
}

now execute this code when the user clicks the upload button:

var data;
getBase64($('input:file'), (r) => { data = r });
$.ajax({
    url: "ajax_php_file.php", // Url to which the request is send
    method: "POST",             // Type of request to be send, called as method
    data: { file: data }
});

php:

<?php
    if (isset($_POST['file'])) {
        $data = $_POST['file'];
        file_put_contents('img.jpg', base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data)));
    }
?>
Poootaatoooo
  • 316
  • 1
  • 10