I am uploading a file to my API built on laravel. In my code below, the data is sent to the API. But how can i get the file that was uploaded to the API ?
Controller
$file = $request->file('imported-file');
$name = $file->getClientOriginalName();
$path ='/Users/desktop/Folder/laravelapp/public/Voice/';
$client = new \GuzzleHttp\Client();
$fileinfo = array(
'message' => 'Testing content',
'recipient' => "102425",
);
$res = $client->request('POST', $url, [
'multipart' => [
[
'name' => 'FileContents',
'contents' => file_get_contents($path . $name),
'filename' => $name
],
[
'name' => 'FileInfo',
'contents' => json_encode($fileinfo)
]
],
]);
API Controller
if (!empty('FileInfo')) {
return response()->json([
'status' => 'error',
'file_content' => $request->file('FileContents'),
'media'=>$request->hasFile('FileContents'),
]);
}
This is the response, i get "file":null,"file_content":{},"media":true
Why is the file content empty when media is showing true meaning there is a file ?
There can be multiple reasons :
Check your content type. Sometimes we forget to specify multipart/form-data and the request is sent with generic application/x-form-urlencoded etc.
Secondly if you are using jQuery, then set :
contentType: false,
processData: false,
cache: false
This will help your form request no getting converted to string payload and not forcing ajax to set content type. try using FormData.
Update : Found similar answer in this post has detailed answer for this.
Related
I have the following Postman request for testing a third party API;
What I am trying to do is convert this into code using Laravel's HTTP class, the code i currently have is;
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true,
'frontfile' => Storage::get('somefrontfile.jpg'),
'sideview' => Storage::get('itsasideview.png'),
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->asForm()
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
But every time I run this, the 3rd party API comes back with Invalid ID, even though if i use Postman with the same ID it works fine.
I cant seem to figure out where i am going wrong with my code;
As #Cbroe mention about attach file before sending post request you can make this like this example:
public function uploadToThridParty()
{
$uploadContents = [
'id' => 'this-is-my-id',
'fileUpload' => true
];
$request = Http::withHeaders(
[
'Accept' => 'application/json',
]
);
$response = $request
->attach(
'frontfile', file_get_contents(storage_path('somefrontfile.jpg')), 'somefrontfile.jpg'
)
->attach(
'sideview', file_get_contents(storage_path('itsasideview.png')), 'itsasideview.jpg'
)
->post(
'https://urltoupload.com/upload', $uploadContents
)
}
Also i think you need remove asForm method because it's override your header accept type to application/x-www-form-urlencoded that is way your exception is Invalid ID
Some third party API would require you to have the request with content type as multipart/form data
you can double check all the headers being pass on your postman request HEADERS tab and view on Hidden headers.
If you indeed need your request to be in multipart/form-data, You can use the multipart options of guzzle.
Although this doesnt seem to be on Laravel HTTP-Client docs, you can simply pass a asMultipart() method in your HTTP request
just check the /vendor/laravel/framework/src/Illuminate/Support/Facades/Http.php for full reference of HTTP client.
You can have your request like this.
public function uploadToThridParty() {
$uploadContents = [
[
'name' => 'id',
'contents' => 'this-is-my-id'
],
[
'name' => 'fileUpload',
'contents' => true
],
[
'name' => 'frontfile',
'contents' => fopen( Storage::path( 'somefrontfile.jpg' ), 'r')
],
[
'name' => 'sideview',
'contents' => fopen( Storage::path( 'itsasideview.jpg' ), 'r')
],
];
$request = Http::withHeaders(['Accept' => 'application/json']);
$response = $request->asMultipart()->post('https://urltoupload.com/upload', $uploadContents );
}
I have an API to save images and files
this is the code to save the image request from the API
$file = $request->file('gambar');
$fileName = $file->getClientOriginalName();
$file->storeAs('images/berita', $fileName);
$berita = new Berita;
$berita->judul = $request->judul;
$berita->kategori_id = $request->kategori_id;
$berita->isi = $request->isi;
$berita->gambar = $fileName;
$berita->tgl = $request->tgl;
$berita->user_id = $request->user_id;
$berita->save();
return response()->json([
'message' => 'Data berita Added Successfully!',
'Added berita' => $berita
], Response::HTTP_OK);
I already try the API in postman, and everything went well, image sucessfully uploaded.
Then on the client side, I'm using HTTP Client from Laravel to POST the data to the API. And here's the code.
$Berita = Http::withToken('xxx')
->attach('attachment', file_get_contents($request->file('gambar')))
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'gambar' => file_get_contents($request->file('gambar')),
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
return $Berita;
All the data send successfully, except the gambar which contains the image that i sent. It says that in my API validation.
The gambar must be a file of type: jpeg, jpg, png.
It thought that means the image that i send is sent as a string, so it didn't receive it as a file.
By the way, here's the Laravel documentation about HTTP Client: https://laravel.com/docs/9.x/http-client#multi-part-requests
Does anyone knows how to correctly using it? I think i've misused it.
I think there is problem with attachment.
return Http::withToken('xxx')
->attach('gambar', file_get_contents($request->file('gambar')), , 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
or
return Http::withToken('xxx')
->attach('gambar', $request->file('gambar'), 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
This is because the server cannot read your data.
You should send the data using the application/x-www-form-urlencoded content type, you can achieve this as Laravel documentation says:
$response = Http::asForm()->post('http://example.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);
I try to send the file via GuzzleHTTP from my application to external API, I make it like this:
public function storeImagesInAmazon(Request $request) {
$uploadFilePath = 'some/endpoint';
$file = $request->file('file');
$client = new Client();
$response = $client->request('POST', $uploadFilePath, [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'multipart/form-data',
],
'multipart' => [
[
'name' => 'file',
'contents' => $file
]
]
]);
$result = json_decode($response->getBody(), true);
return [
'hashedID' => $result['hashedID']
];
}
The error I get is:
Server error: POST some/endpoint resulted in a 500 Internal Server Error response:\n
Errorerror while processing file: Failed to process file: part was null
I tested it via Postman, adding key = 'file', value = 'some_file.pdf' in Body form-data, I am sure file is correct, I mean it isn't damaged, I tried to post different files large one, a small one, pdf or jpg/png.
But I still have this issue and I can't find a solution for this.
I found this solution Guzzle form_params not accepting array
what I'm trying to say is, you need $option as your next param like in that post
$response = $client->post('api', $options);
and that $option is where your headers or multipart or other options goes as per documentation. i already tried using $options and its worked in my case.
What I have till now
Right now I have a working oauth2 authentication between a laravel user and the dropbox API. Every user can upload files to their personal folder.
The Problem
After Uploading a file with laravel with the Dropbox API v2 I can see that there is a empty (0 Bytes) file uploaded.
Used to accomplish this task:
Laravel
Guzzle
Dropbox API Library
What am I missing?
The Code
My function for processing a form looks like this:
$formFile = $request->file('fileToUpload');
$path = $formFile->getClientOriginalName();
$file = $formFile->getPathName();
$result = Dropbox::files()->upload($path, $file);
return redirect('dropboxfiles');
And my files->upload function in my Dropbox Library looks like this:
$client = new Client;
$response = $client->post("https://content.dropboxapi.com/2/files/upload", [
'headers' => [
'Authorization' => 'Bearer '.$this->getAccessToken(),
'Content-Type' => 'application/octet-stream',
'Dropbox-API-Arg' => json_encode([
'path' => $path,
'mode' => 'add',
'autorename' => true,
'mute' => true,
'strict_conflict' => false
])
],
'data-binary' => '#'.$file
]);
The file, as I said, gets uploaded successfully. Correct name, but 0 Bytes. So empty file.
Thank you so much in advance for your help!
Update
With the following code I made it work. My question is though if there is a better "Laravel-Like" Solution instead of using fopen?
$response = $client->post("https://content.dropboxapi.com/2/files/upload", [
'headers' => [
'Authorization' => 'Bearer '.$this->getAccessToken(),
'Dropbox-API-Arg' => json_encode([
'path' => $path,
'mode' => 'add',
'autorename' => true,
'mute' => true,
'strict_conflict' => false
]),
'Content-Type' => 'application/octet-stream',
],
'body' => fopen($file, "r"),
]);
How #Greg mentioned (see cross-linking reference) I was able to solve this issue by using
'body' => fopen($file, "r"),
instead of
'data-binary' => '#'.$file
This is, how Greg mentioned, because data-binary is used in Curl requests. Other HTTP Clients, like Guzzle in my case use different names.
I am trying to post image content as a parameter of the multiform request. The following code works.
$read_image = base64_encode(file_get_contents('Large.jpg'));
$client = new Client(['debug' => true ,'handler' => $stack,]);
$request = $client->Request(
'POST',
'https://mylandoapp.lndo.site/testdrive/post',
[
'multipart' =>
[
[
'name' => 'image',
'contents' => $read_image,
],
],
]
);
I am able to get the value using following code.
$data =$request->request->all();
$my_image = $data[$image];
When I try to add the file name, the image content is an empty array.
$request = $client->Request(
'POST',
'https://mylandoapp.lndo.site/testdrive/post',
[
'multipart' =>
[
[
'name' => 'image',
'contents' => $read_image,
'filename' => 'custom_filename.txt',
],
],
]);
How can I pass file name a well as file content using multiform post request?
Could be trivial, but first check that is actually a Guzzle issue and not a php memory limit issue. Base64 encoding a "Large.jpg" will triple the string length of $read_image. Check the php error log to see if your not running out of buffer length. I would try with a smaller JPEG first.