How can I create/save a file from BLOB in php? - php

What I did so far:
Okay, so i create a blob file (wav content) and it is stored under blob:http://localhost/cf6fefdc-352e-4cec-aef8-03af6d0d0ef6.
When i put this URL into my browser, it plays the file.
What i need to do
I want to convert the blob into an actual file, that i want to store on my webserver.
I'm handing the blob object over to a php file via AJAX
$.ajax ({
type: "POST",
url:"path/to/my/file.php",
data: {thefile : blob} ,
success: function(text) {
console.log(text);
},
error:function(){
console.log("Error")
}
});
That works. If I print_r the variable it returns [object Blob]
My PHP
<?php
$file = $_POST['thefile'];
print_r($file);
Can anyone tell me how I can convert and save the file to my server from there on?

In your file.php add this code
$filePath = 'uploads/' . $_POST['thefile'];
$tempName = $_FILES['thefile']['tmp_name'];
if (!move_uploaded_file($tempName, $filePath)) {
echo 'Problem saving file: '.$tempName;
die();
}
// success report
echo 'success';

Related

$.ajax to ask php read file and return

I want use AJAX to ask PHP to read a file and return data. The problem is, PHP can read the file but AJAX cannot get the data.
$.ajax({
type: 'GET',
timeout : 1000,
url : '../tools/test2.php', //read file and echo
dataType : 'json',
cache : false,
beforeSend: function() {
$("#demo2").val('loading..')
},
success : function(data) {
$("#demo2").val('message:' + data) //this never can run
}
});
//test2.php
<?php
header("Content-type:text/html");
$fileName = "./testFile.txt";
$file = fopen($fileName, "r");
echo fgets($file);
fclose($file);
?>
You said:
dataType : 'json',
And then you said:
header("Content-type:text/html");
So jQuery tried to parse your HTML as JSON, failed and ran the error handler (which does nothing because you didn't write one) instead of the success handler.
Fix your dataType (you can just remove it so that jQuery will respect the Content-Type header) or rewrite the PHP so it returns JSON instead of HTML.
(If you are actually returning plain text (since you have a .txt file) then say Content-Type: text/plain).

How to use ajax to execute php function that will push a file to the browser?

I'm trying to write a method in a php class that will use ajax to execute a php function that will push a file back to the browser.
It seems like its trying to write the file to the modx log, getting a lot of binary garbage in there.
Here is the method:
public function pushDocuments($formdata){
$data = $formdata['formdata'];
$file = MODX_PROTECTED_STORAGE . $data['target'];
$file_name = basename($file);
if (file_exists($file)) {
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
};
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => array(),
);
$output = $this->modx->toJSON($output);
return $output;
}
and here is the jquery:
$('.btn-get-document').click(function(){
var target = $(this).attr('data-target');
var postdata = {"snippet":"DataSync", "function":"pushDocuments", "target": target}; // data object ~ not json!!
console.log('target = ' + target + postdata );
$.ajax({
type: "POST",
url: "processors/processor.ajax.generic/",
dataType : "json",
cache : false,
data: postdata, // posting object, not json
success: function(data){
if(data.status == 'success'){
console.log("SUCCESS status posting data");
}else if(data.status == 'error'){
console.log("error status posting data");
}
},
error: function(data){
console.log("FATAL: error posting data");
}
});
});
it's running through the scripts and giving a success in the console [because I am forcing success] but no file is prompted for download and the binary garbage shows up in the modx log
What am I doing wrong?
In order to download a file, you'd have to use JS to redirect to the file's location. You can't pull the file contents through AJAX and direct the browser to save those contents as a file.
You would need to structurally change your setup. For instance, your PHP script can verify the existence of the file to be downloaded, then send a link to JS in order to download the file. Something like this:
if ( file_exists( $file )) {
$success_message = array(
'file_url' => 'http://example.com/file/to/download.zip'
);
}
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => $success_message
);
Then modify the "success" portion of your AJAX return like this:
success: function( data ) {
if ( data.status == 'success' ) {
location.href = data.success_messages.file_url;
} else if ( data.status == 'error' ) {
console.log( 'error status posting data' );
}
},
Since you're directing to a file, the browser window won't actually go anywhere, so long as the file's content-disposition is set to attachment. Typically this would happen if you directed to any file the browser didn't internally handle (like a ZIP file). If you want control over this so that it downloads all files (including things the browser may handle with plugins), you can direct to another PHP script that would send the appropriate headers and then send the file (similar to the way you're sending the headers and using readfile() in your example).
#sean-kimball,
You might want to extend MODX's class based processor instead:
https://github.com/modxcms/revolution/blob/master/core/model/modx/processors/browser/file/download.class.php
It does the download from any media source and also access checking if you want.
Its implementation on manager side is:
https://github.com/modxcms/revolution/blob/master/manager/assets/modext/widgets/system/modx.tree.directory.js#L553
Back to your case, these examples might bring you some ideas.
JS Example:
$.ajax({
type: "POST",
// read my note down below about connector file
url: "assets/components/mypackage/connectors/web.php",
dataType : "json",
cache : false,
data: {
action: 'mypath/to/processor/classfile'
}
success: function(data){
},
error: function(data){
console.log("FATAL: error posting data");
}
});
Processor example:
<?php
require_once MODX_CORE_PATH . 'model/modx/processors/browser/file/download.class.php';
class myDownloadProcessor extends modBrowserFileDownloadProcessor {
// override things in here
}
return 'myDownloadProcessor';
For this, I also suggest you to use MODX's index.php main file as the AJAX's connector so the $modx object in processor inherits the access permission as well.
http://www.virtudraft.com/blog/ajaxs-connector-file-using-modxs-main-index.php.html

Issue on Posting Image to a PHP File

I am trying to capture a highcharts chart and POST it to a PHP file
(result.php). I am able to capture image right now but I do not know how to POST captured image to another file. so far I have this code which is returning a PNG image
function postChart(chart) {
var obj = {},chart;
obj.svg = chart.getSVG();
obj.type = 'image/png';
obj.async = true;
exportUrl = 'http://export.highcharts.com/';
$.ajax({
type: "POST",
url: exportUrl,
data: obj,
cache:false,
async:true,
crossDomain:true,
success: function (data) {
// How to Send Image to result.php
},
error: function(data) {
}
});
}
and this result.php file as:
<?php
$content = $_POST['Not Sure What!'];
echo $content;
Now can you please let me know what can I put in
success: function (data) {
// How to Send Result to another Page
},
to post the image to result.php and how should I modify the result.php. Thanks
You can just use the highchart's exportChart API Like
function postChart(chart) {
chart.exportChart({
url : 'path/to/result.php',
type: 'image/png',
filename: 'my-chart'
});
}
Then from result.php you will be able to access the $_POST variable. which will contain following array, where $_POST['svg'] is the image in svg format.
array (
'filename' => 'my-chart',
'type' => 'image/png',
'width' => '0',
'scale' => '2',
'svg' => '',
)
You can then use the highchart's server side script to convert the image from svg to your desired format.
If you do not like to use java library for the conversion, you can also try this
Happy Coding!!
This works only if your php-script is somewhere on http://export.highcharts.com/
(Because you set the crossDomain property to true)
In your ajax method:
Change:
data: obj,
TO:
data: {
objName: obj,
}
Then in the result.php:
<?php
var_dump($_FILES['objName']);
// If you're interested, what else is inside $_FILES
var_dump($_FILES);
Not entirely sure what you're asking. This may be of some help though.
When working with files on upload use $_FILES. Its exactly like $_POST but for files.
Theres a selection of variables you can gather from the file using $_FILES.
<?
$tempname = $_FILES['file']['tmp_name'];
$filetype = $_FILES["file"]["type"];
$filesize = $_FILES['file']['size'];
?>
In the case above this references the file with a name of "file".

passing base64string to php file using ajax and post

Using mobile apllication here, I am sending image encoded data to php file using post method and getting the image url from the php file. The problem here is, I am not getting proper image while am sending string using ajax. When I place the image data manually, I am able to view the image, but when sending the image data using ajax call, unable to view the image.
<?php
//$image = $_POST['uploadedfile'];//not working if an ajax call is made what is the issue here
$image ="base64 string of an image here";//working if i place base 64 string here
$binary = base64_decode($image);
$fileName = time() . ".jpeg";
file_put_contents('images/' . $fileName, $binary);
if (file_exists('images/' . $fileName)) {
$myjson12 = "[";
$myjson12.='{';
$myjson12.='"Certificate":"http://domain/demo/images/'.$fileName.'"';
$myjson12.='}';
$myjson12.="]";
echo "$myjson12";
} else {
echo 'FAILURE';
}
?>
When I am accessing the file url and sending the parameter value the output is coming as url is too long: www.domain.com/getdata.php?uploadedfile=base64stringvalue;
here is my ajax call
$.ajax({
type: "POST",
url: "www.domain.com/getdata.php",
data: { "uploadedfile": c.toDataURL("image/jpeg") },
// dataType: "json",
success: function (response) {
console.log(response + "Sri");
$("#loadImg").hide();
alert("Success");
},
error: function (data) {
$("#loadImg").hide();
alert("Connection Failed");
}
});

How do I get a variable from a different php file?

I have the following code in my index.php page:
// Write the resulting JSON to a text file
var jsontext = $('#code-output').text();
$.ajax({
url: 'writetxt.php',
type: 'POST',
data: { data: jsontext },
success: function(result) {
$('#code-output').hide().fadeIn('slow');
}
});
And this is the contents of writetxt.php:
// Generating a unique filename using the date and time plus a random 4-digit string
$filename = date("YmdHis-") . rand(1337,9001);
// Making the JSON text file
$jsontext = $_POST["data"];
$fp = fopen("jsontxt/" . $filename . ".txt","w");
fwrite($fp,$jsontext);
fclose($fp);
Basically, a new text file is created every time a change is made to the JSON text. How do I access $filename from the index.php file?
Either include the file in the other one
require_once('my_file.php');
echo $varFrom_my_file;
or set it to a session variable
session_start();
$_SESSION['foo'] = "Bar";
Then the other file
echo $_SESSION['foo'];
I'm assuming index.php has some content along with PHP variable? Using include will include that content. Use a session variable to go across pages.
PHP Sessions
Return the value of $filename as a JSON string
echo json_encode(array('filename'=>$filename);
Then pull it out of the result var
result.filename
(untested)

Categories