Trying to send filestream with other data to an API , but it return the error:
The video provided was null
Here is my code:
function create_video($files) {
$api = "http://api.brightcove.com/services/post";
$local_file_list = $files['file']['tmp_name'];
foreach ($local_file_list as $local_file) {
try {
$fp = fopen($local_file, 'r');
$ch = curl_init();
if (FALSE === $ch) {
throw new Exception('failed to initialize');
}
//"video":{"name":"test","shortDescription":"test","startDate":1432282741000,"endDate":null}
$request = 'json={"params":{"encode_to":"MP4","create_multiple_renditions":"True","token":"' . WRITE_TOKEN . '"},"method":"create_video"}';
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($local_file));
$content = curl_exec($ch);
if (FALSE === $content) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
die(var_dump(json_decode($content)));
return json_decode($content);
} catch (Exception $e) {
trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
}
}
}
Few things need to note:
CURL does not return error , so it may not caused by CURL
The filesize($local_file) has return the correct file size
fopen($local_file, 'r'); return the stream type content, so the file is exist
How to fix that? Thanks
API reference:
https://docs.brightcove.com/en/video-cloud/media/references/reference.html#Video_Write
Update:
Thanks for helping , but it now return another error:
POST methods require valid JSON-RPC in the POST body, with "method" and "params" properties
I have some idea of that as when I look at the request payload, it is slightly different from the correct one:
Current my version:
------WebKitFormBoundary8VABz8KuNRE8Hepd
Content-Disposition: form-data; name="file[0]"; filename="big_buck_bunny.mp4"
Content-Type: video/mp4
------WebKitFormBoundary8VABz8KuNRE8Hepd--
The correct version
------WebKitFormBoundaryCAB6WEANBJxoB3Op
Content-Disposition: form-data; name="JSONRPC"
{"params":{"video":{"name":"test","shortDescription":"test","startDate":1432282741000,"endDate":null},"encode_to":"MP4","create_multiple_renditions":"True","token":"VyocgALDnxU8HPvmnSnckgmXjoPlYWomc2La5Tn-evuAfsnSPJJoow.."},"method":"create_video"}
------WebKitFormBoundaryCAB6WEANBJxoB3Op
Content-Disposition: form-data; name="filePath"; filename="big_buck_bunny.mp4"
Content-Type: video/mp4
------WebKitFormBoundaryCAB6WEANBJxoB3Op
Content-Disposition: form-data; name="JSONView"
{"params":{"video":{"name":"test","shortDescription":"test","startDate":1432282741000,"endDate":null},"encode_to":"MP4","create_multiple_renditions":"True","token":"VyocgALDnxU8HPvmnSnckgmXjoPlYWomc2La5Tn-evuAfsnSPJJoow.."},"method":"create_video"}
------WebKitFormBoundaryCAB6WEANBJxoB3Op--
You can wrap the file to upload into CURLFile (PHP >= 5.5):
$cfile = new CURLFile($local_file, 'video/mp4', basename($local_file));
Then, add to CURLOPT_POSTFIELDS, making it part of the whole request:
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => $cfile,
'JSONRPC' => '{"params":{"encode_to":"MP4","create_multiple_renditions":"True","token":"' . WRITE_TOKEN . '"},"method":"create_video"}';
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
Before PHP 5.5 you can use the # to indicate a file:
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => "#$local_file",
'JSONRPC' => '{"params":{"encode_to":"MP4","create_multiple_renditions":"True","token":"' . WRITE_TOKEN . '"},"method":"create_video"}';
]);
Related
I have 2 Laravel APIs.
One API requesting a file from the second with a curl.
I want to get the file as an UploadedFile without calling to new UploadedFile().
Or as alternative I want to create UploadedFile with the response contant without saving it as a temp file (and then calling new UploadedFile() with a temp path).
First API for requesting the file:
$url = 'http://someurl.org';
$CR = curl_init();
curl_setopt($CR, CURLOPT_URL, $url);
curl_setopt($CR, CURLOPT_FAILONERROR, true);
curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($CR, CURLOPT_HEADER, 1);
$response = curl_exec($CR);
curl_close($CR);
return $response;
Response print screen
Second API:
public function getFile(string $fileId)
{
$recordedFile = RecordedFile::where('file_id', $fileId)->first();
if (!$recordedFile) {
return response(['message' => 'file not found'], 400);
}
$headers = [
'Content-type' => Storage::mimeType($recordedFile->path),
'Content-Disposition' => 'attachment; filename=' . $recordedFile->original_name .''
];
$file = Storage::get($recordedFile->path);
return response($file, 200, $headers);
}
Found this.
https://gist.github.com/waska14/f3be9c1cf0731a85753c9f34e9fca348
The FileHelper::fromBase64($this->input('file')) part helped me.
Hy Everyone,
I am using this code to download file from Dropbox Version 2 Php Api.But I don't get success yet in File downloading.Lets have a look on the script which i am using
function dbx_get_file($token, $in_filepath, $out_filepath)
{
$out_fp = fopen($out_filepath, 'w+');
if ($out_fp === FALSE)
{
echo "fopen error; can't open $out_filepath\n";
return (NULL);
}
$url = 'https://content.dropboxapi.com/2/files/download';
$header_array = array(
'Authorization: Bearer ' . $token,
'Content-Type:',
'Dropbox-API-Arg: {"path":"' . $in_filepath . '"}'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
curl_setopt($ch, CURLOPT_FILE, $out_fp);
$metadata = null;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$metadata)
{
$prefix = 'dropbox-api-result:';
if (strtolower(substr($header, 0, strlen($prefix))) === $prefix)
{
$metadata = json_decode(substr($header, strlen($prefix)), true);
}
return strlen($header);
}
);
$output = curl_exec($ch);
if ($output === FALSE)
{
echo "curl error: " . curl_error($ch);
}
curl_close($ch);
fclose($out_fp);
return($metadata);
} // dbx_get_file()
Calling this Function Here.
dbx_get_file("<Access-token>", '/Screenshot_1.png', 'Screenshot_1.png');
I also replaced this "Access-token" with my Dropbox O-auth 2 Access Token.
Please suggest me the answer what i am doing wrong?Or is there any other way to download File from Dropbox using DropBox Version 2 PHP Api.
Thanks
I have done it using Requests Library https://github.com/rmccue/Requests/
Here is my Code
include('Requests-master/library/Requests.php');
Requests::register_autoloader();
$token="Your Access Token is here";
$response =
Requests::post("https://content.dropboxapi.com/2/files/download", array(
'Authorization' => "Bearer ".$token,
'Dropbox-Api-Arg' => json_encode(array('path' => '/Screenshot_1.png')),
));
$fileContent = $response->body;
/*Download the file using file_put_contents method*/
file_put_contents("Screenshot_1.png",$fileContent);
$metadata = json_decode($response->headers['Dropbox-Api-Result'], true);
echo "File " . $metadata["name"] . " has the rev " . $metadata["rev"] . ".\n";
File is downloading Successfully... :)
So I've seen many examples of uploading an image via PHP using move_uploaded_file, but from the way that sounds, that would be a PHP script that resides on the server. In my case, I'm not trying to handle an uploaded file. I'm trying to submit a POST request and actually have the binary content of the file inserted with the HTTP POST request.
For example, my PHP script should be able to submit a form and include an image in its HTTP POST data, but I can't seem to figure this out or find valid examples specifically for doing this.
To further clarify, I am using CURL within PHP to submit this multipart/form-data.
Here's an example of what I have now:
function GetPostData($filename) {
if(!$filename) {
echo "The image doesn't exist ".$filename;
} else {
$data = [
'device_timestamp' => time(),
'photo' => '#'.$filename
];
return $data;
}
}
function SendRequest($url, $post, $data, $userAgent, $cookies) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://i.example.com/api/v1/'.$url);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_PROXY, 'http://192.168.1.21:8080');
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if($post) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if($cookies) {
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
} else {
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
}
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'code' => $http,
'response' => $response,
];
}
.
$data = GetPostData($filename);
$post = SendRequest('media/upload/', true, $data, $agent, true);
But when I submit the image via the PHP script, this is what it looks like when I inspect the network traffic.
Content-Type: multipart/form-data; boundary=------------------------eee3f953c516cc55
Connection: close
--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="device_timestamp"
1491023582
--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="photo"
#/home/user/Desktop/square.jpeg
--------------------------eee3f953c516cc55--
Isn't the POST data supposed to contain the binary output of the image? How would the server save the image otherwise if just the path of the file is submitted in the form and not the actual image?
In other words, just like you would go to the terminal and type cat image.jpg, that's what I need PHP to submit in its form.
Solved my own problem by changing
function GetPostData($filename) {
if(!$filename) {
echo "The image doesn't exist ".$filename;
} else {
$data = [
'device_timestamp' => time(),
'photo' => '#'.$filename
];
return $data;
}
}
to this:
function GetPostData($filename) {
if(!$filename) {
echo "The image doesn't exist ".$filename;
} else {
$data = [
'device_timestamp' => time(),
'photo' => file_get_contents($filename)
];
return $data;
}
}
You have required to use in then you can easly uploded image
ex:-
<form action="" method="post" enctype="multipart/form-data">
</form>
PHP Code Required
<?php
if(isset($_POST['submit']))
{
$filename=$_FILES['Yourfilename']['name'];
$filetempname=$_FILES['Yourfilename']['tmp_name'];
$fname=md5($_SERVER['REMOTE_ADDR'].rand()).$filename;
$filepath1="uploads/folder name/".$fname;
move_uploaded_file($filetempname,$filepath1);
?>
Recently I work with an API that require send the data in JSON-RPC format.
And I construct like that
function create_video($files) {
$api = "http://api.brightcove.com/services/post";
$local_file_list = $files['file']['tmp_name'];
foreach ($local_file_list as $local_file) {
try {
$ch = curl_init();
if (FALSE === $ch) {
throw new Exception('failed to initialize');
}
$params = array(
"encode_to" => "MP4",
"create_multiple_renditions" => "True",
"token" => WRITE_TOKEN,
"file" => #$local_file
);
$request = json_encode(array('jsonrpc' => '2.0', 'method' => 'create_video', 'params' => $params));
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
if (FALSE === $content) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
die(var_dump(json_decode($content)));
return json_decode($content);
} catch (Exception $e) {
trigger_error(sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage()), E_USER_ERROR);
}
}
}
The problem is , it create the incorrect json structure comparing to the correct one.
Request Payload of my version
------WebKitFormBoundary8VABz8KuNRE8Hepd
Content-Disposition: form-data; name="file[0]"; filename="big_buck_bunny.mp4"
Content-Type: video/mp4
------WebKitFormBoundary8VABz8KuNRE8Hepd--
Request Payload of correct version
------WebKitFormBoundaryCAB6WEANBJxoB3Op
Content-Disposition: form-data; name="JSONRPC"
{"params":{"video":{"name":"test","shortDescription":"test","startDate":1432282741000,"endDate":null},"encode_to":"MP4","create_multiple_renditions":"True","token":"VyocgALDnxU8HPvmnSnckgmXjoPlYWomc2La5Tn-evuAfsnSPJJoow.."},"method":"create_video"}
------WebKitFormBoundaryCAB6WEANBJxoB3Op
Content-Disposition: form-data; name="filePath"; filename="big_buck_bunny.mp4"
Content-Type: video/mp4
------WebKitFormBoundaryCAB6WEANBJxoB3Op
Content-Disposition: form-data; name="JSONView"
{"params":{"video":{"name":"test","shortDescription":"test","startDate":1432282741000,"endDate":null},"encode_to":"MP4","create_multiple_renditions":"True","token":"VyocgALDnxU8HPvmnSnckgmXjoPlYWomc2La5Tn-evuAfsnSPJJoow.."},"method":"create_video"}
------WebKitFormBoundaryCAB6WEANBJxoB3Op--
And the correct website that send data, you may enter the form to test
http://docs.brightcove.com/en/video-cloud/media/samples/create_video.html#request
And the API reference(create video)
https://docs.brightcove.com/en/video-cloud/media/references/reference.html#Video_Write
Thanks a lot for helping.
The documentation of their API reference (the second link) states:
For write requests, he data submitted to the media write API should be
in JSON format, encoded as a form parameter named "json". The JSON
document should include a "method" field and a "params" field, and the
examples you publish should show the whole body of the POST request:
json=
So, just replace:
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
with:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'json=' . $request);
and it should be working then. I got error "invalid token" instead of "Could not find JSON-RPC." by replacing the code above.
I am trying to upoad attachments to a specific case using REST API which I have successfully completed.
the files are being uploaded to that specific case. and I am using base64_encode to send binary data to SalesForce as they required the binary data to be sent.
but the issue is that when I see the files in the sales force control panel,
all the files are listed there and their size is correct, name is correct etc
but when I view/download any file uploaded with the script it doesn't open. the file shows errror.
ie. when I upload an png image with the rest API, I wont be able to open the image after downloading from the sales force control panel.
Can any one please help?
I think sales force might not decode the uploaded files back from base64_encode, is that right?
Thanks in advance
here is the code
$fp = fopen($file, 'r');
$db_img = fread($fp, filesize($file));
$db_img = addslashes($db_img);
$db_img = base64_encode($db_img);
and then after encoding I am concatenating $db_img within the body element like this
...................
...'.$db_img.'...
.................;
I figured it out myself. I thought I should post the answer as well. I am using the following function to add attachments to the Case Object.
No need to convert to base64 at all
public function add_attachment($case_id, $full_file_path, $file_name) {
$url = $this->instance_url."/services/data/v33.0/chatter/feed-elements";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
$headers = array();
$headers[] = "Authorization: OAuth $this->access_token";
$headers[] = 'Content-Type: multipart/form-data; boundary=a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq';
$post_text = '--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Disposition: form-data; name="json"
Content-Type: application/json; charset=UTF-8
{
"body":{
"messageSegments":[
{
"type":"Text",
"text":"Task Attachment"
}
]
},
"capabilities":{
"content":{
"description":"Task Attachment",
"title":"'.$file_name.'"
}
},
"feedElementType":"FeedItem",
"subjectId":"'.$case_id.'"
}
--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Disposition: form-data; name="feedElementFileUpload"; filename="'.$file_name.'"
Content-Type: image/png
'. file_get_contents($full_file_path).'
--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq--';
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_text);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$response_json = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
//print_r($info);
if ( $status != 201 ) {
$this->errors[] = "Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl);
return FALSE;
}
$this->status = $status;
$this->curl_error = curl_error($curl);
$this->curl_errno = curl_errno($curl);
return json_decode($response_json,TRUE);
}