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
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
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?
(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)));
}
?>