upload video to DailyMotion using GuzzleHttp - php

I'm trying to upload a video using Laravel and GuzzleHttp to DailyMotion. Here's my code:
$file = "3.mp4";
$fields["file"] = fopen($file, 'rb');
$res = $client->post($upload_url, [
'headers' => ['Content-Type' => 'multipart/form-data'],
$fields
]);
$data3 = $res->getBody();
$response_upload_video = json_decode($data3,true);
echo "<br>Getting dm upload video response: ";
print_r($response_upload_video);
$upload_url is a dynamically generated URL passed by DailyMotion. Upon executing the code above, I'll always get this error:
Production.ERROR: GuzzleHttp\Exception\ClientException:
Client error:
POST
http://upload-02.sg1.dailymotion.com/upload?uuid=werewkrewrewrwer&seal=pppppppppppppppp`resulted
in a 400 Bad Request response:
{"error":"invalid content range","seal":"yyyyyyyyyyyyyyyyyy"}
in /home/vagrant/Code/svc-titus/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:111
But I can upload video to the same upload URL using Postman, as displayed below:

i don't think you need to specify content-type header guzzle will decide it automatically when you provide it a resource also the path of your video here seems problematic if video is stored at public directory you need to use public_path or respective path helper function to get its physical path
below should work in guzzleHttp 6 check sending form files here
http://docs.guzzlephp.org/en/latest/quickstart.html#uploading-data
$file = "3.mp4";
$res = $client->post($upload_url, [
'multipart' => [
[
'name' => 'file',
'contents' => fopen(base_path($file), 'r') // give absolute path using path helper function
]
]
]);
$data3 = $res->getBody();
$response_upload_video = json_decode($data3,true);
echo "<br>Getting dm upload video response: ";
print_r($response_upload_video);

Related

How to open the PDF generated in new tab

I have a Leave application project that generates a PDF file.
this is the code that generates the pdf after I click submit.
$id = DB::table('leave')->where('user_id', auth()->user()->id)->max('id');
$data = leave::where('id', $id)->select('*')->get();
$filename = auth()->user()->name." - S - ". "LEAVE - ".$randomString->randomString(8)."-".$request->filing_date.".pdf";
$path = storage_path('app/leave_file/'.$filename);
PDF::loadView('pdf_views.leave_pdf', $data[0])->setPaper('legal')->save($path);
if(file_exists($path)){
DB::table('leave_files')->insert([
'filename' => $filename,
'leave_id' => DB::table('leave')->where('user_id', auth()->user()->id)->max('id'),
]);
}
return redirect()->route('leave')->with('success', "success");
I wonder if I can make the newly generated pdf open in the new tab after I click submit on my leave application. thank you to anyone who can help
According to the Laravel docs this is what you need: https://laravel.com/docs/9.x/responses#file-responses
File Responses
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
Use the Cache Facade, to store the generated pdf temporary.
$uuid = Str::uuid();
return response()->stream(function () use ($uuid) {
echo Cache::remember($uuid, 300, function() {
return 'genertated pdf content'
});
}, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => sprintf('attachment; filename=%s;', $uuid),
]);
Create a route to access to cached file. Name the route.
Now you can open it in a new tab from you frontend e.g. Generate the route with route('routename', ['param' => 123]) and pass it to your FE with a REST endpoint for example.
window.open(url,'_blank');

Google Drive API upload 1 fiile from php

on output when open page -
File ID: 1qG8tteyVhAbB_rbu_VUvaE9ReqnSjEAh...
But on google drive no new files are created. I want upload file to cron but now i want only download test.pdf and end.
require_once './google-api-php-client/vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;
function uploadBasic()
{
try {
$client = new Client();
//$client->useApplicationDefaultCredentials();
$client->setAuthConfig('./google-api-php-client/1710-6c50418be6b2.json');
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$fileMetadata = new Drive\DriveFile(array(
'parents' => ['225qhcKKyf8Ot0IhrRxRtqgHNTxLV1LiyI'],
'name' => 'test.pdf',
'mimeType' => 'application/pdf'));
$mimeType=mime_content_type($fileMetadata);
$content = file_get_contents('https://example.com/test.pdf');
$file = $driveService->files->create($fileMetadata, array([
'data' => $content,
'mimeType' => 'application/pdf',
'uploadType' => 'multipart',
'fields' => 'id']));
printf("File ID: %s\n", $file->id);
return $file->id;
} catch(Exception $e) {
echo "Error Message: ".$e;
}
}
uploadBasic();
how to debug issue
The fastest way to debug this is to do a File.list. This will tell you if in fact the file was uploaded.
You are not setting parents yin your meta data, so the file will have been uploaded to the root directory.
service account
Remember if you are using a service account that the files are uploaded into the service accounts google drive account, not your personal drive account.
To upload to your personal drive account you would need to create a directory on your drive account, share that directory with your service account using the service account email address. The service account email address can be found in the json key file its the only one with an #.
Then set parents in the meta data to the folder on your drive account
$fileMetadata = new Drive\DriveFile(array(
'parents' => { 'FolderId' }
'name' => 'ASB-Background-3.png'));
File 0 size error after edit
You edited your question. It originally stated you were doing this
$content = file_get_contents('./google-api-php-client/ASB-Background-3.png');
It is bad practice to update your question and change your code. It changes the answer to your question and in this case your error message.
That being said From the documentation for file_get_contents
file_get_contents — Reads entire file into a string
There is nothing in the documentation that states that this method could load a file from a url. So your edit changing to a URL is probably not going to work.
file_get_contents('https://example.com/test.pdf');
Your file is uploading with 0 because your not giving it a file. Download that file on to the machine running it and then send it, or write our own method which will accept a url and return a string file conents.
upload image
Files are uploaded in two parts first the fileMetadata and then the file itself.
MimeType must be properly set to that of the file you are uploading. file_get_contents will only work on a file that is currently accessible by your code.
If the file size is 0 make sure
to check the most recent uploaded file. every create will create a new file.
ensure that your code has access to the file you are uploading.
make sure the mimeType is correct.
Sample.
try {
$client = new Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$fileMetadata = new Drive\DriveFile(array(
'name' => 'photo.jpg'));
$content = file_get_contents('../files/photo.jpg');
$file = $driveService->files->create($fileMetadata, array([
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
'fields' => 'id']));
printf("File ID: %s\n", $file->id);
return $file->id;
} catch(Exception $e) {
echo "Error Message: ".$e;
}

Download File With Guzzle

I'm attempting to retrieve a file attachment with Guzzle. The file isn't available directly through an endpoint, but the download is initiated via the end point and downloaded to my browser. Can I retrieve this file with Guzzle?
I successfully login to the site, but what is saved to my file is the html of the site not the download. The file contents seems to come through when I make the request with insomnia rest client, but not with Guzzle.
$client = new GuzzleHttp\Client();
$cookieJar = new \GuzzleHttp\Cookie\CookieJar();
$response = $client->post('https://test.com/login', [
'form_params' => [
'username' => $username,
'password' => $password,
'action' => 'login'
],
'cookies' => $cookieJar
]);
$resource = fopen(__DIR__.'/../../feeds/test.xls', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$response = $client->request('GET', 'https://test.com/download', ['sink' => $stream]);
If you want to perform an authentication step and then a download step, you'll need to make sure the cookies are persisted across both requests. Right now you're only passing your $cookieJar variable to the first one.
The explicit way of doing this would be to add it to the options for the second request:
['sink' => $stream, 'cookies' => $cookieJar]
but it might be easier to take advantage of the option in the client constructor itself:
$client = new GuzzleHttp\Client(['cookies' => true);
That means that every request (with that client) will automatically use a shared cookie jar, and you don't need to worry about passing it into each request separately.
You should send Content-Disposition header in order to specify that the client should receive file downloading as a response. According to your GET HTTP request which will capture the contents into the $stream resource, finally you can output these contents to browser with stream_get_contents.
<?php
// your 3rd party end-point authentication
...
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="test.xls"');
$resource = fopen(__DIR__.'/../../feeds/test.xls', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$response = $client->request('GET', 'https://test.com/download', ['sink' => $stream]);
echo stream_get_contents($stream);

forcing guzzle to download the zip files

Need help downloading the the json response zip files.
I am using guzzle json response from the remote server which returns filenames and modification dates to me. i want to download all these zip files to my storage folder of local server..
so it would work like this
remote server gives json response filenames
i take the filenames and create my link and force guzzle to download those files to my local server.
Here is my code
ini_set('max_execution_time', '0');
$url = "https://feeds.example.com/zips/publisher/";
try
{
$client = new GuzzleHttp\Client();
$res = $client->request('GET', $url, [
'auth' => ['username', 'password'],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]);
$responses = json_decode($res->getBody()->getContents());
foreach ($responses->incrementalFeed as $feed)
{
$downloadLink = $url . $feed->name;
$client->get($downloadLink, ['auth' => ['username', 'password']]);
Storage::put($feed->name, $downloadLink);
}
}
catch (ClientException $e) {
echo $e->getMessage();
}
it downloads all the zip files to my storage folder but all the file are like 1kb , empty .. however in remote website those files are like from 10mb to 600mbs
what am i doing wrong here?
You’re not downloading anything.
You need to use guzzle again to download the files
e.g
$response = $client->get($downloadLink);
Storage::put($feed->name, $response->getBody());

Guzzle 6 download file

Need help using Guzzle 6 for downloading a file from a rest API. I don't want the file to be saved locally but downloaded from web browser. Code so far below, but believe I am missing something?
<?php
//code for Guzzle etc removed
$responsesfile = $client->request('GET', 'documents/1234/content',
[
'headers' => [
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/pdf',
'Content-Type' => 'Content-Disposition: attachment; filename="test"'
]
]
);
return $responsesfile;
?>
Just do research inside Guzzle's docs, for example here
Pass a string to specify the path to a file that will store the contents of the response body:
$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
Pass a resource returned from fopen() to write the response to a PHP stream:
$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);
Pass a Psr\Http\Message\StreamInterface object to stream the response body to an open PSR-7 stream.
$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);
stream_for is deprecated in version 7.2. You can use
GuzzleHttp\Psr7\Utils::streamFor($resource) instead.
First of all, Content-Type header only makes sense when you send something (POST/PUT), but not for GET requests.
Secondly, what is your issue? Guzzle by default does not store the response body (file) somewhere, so you can work with it inside your app, like $responsesfile->getBody().

Categories