I'm building an API using Symfony and I am trying to upload a generated file directly in a Backblaze bucket. I'm struggling to build the request and send the file.
Here is the code of my endpoint :
$filename = "fiche-technique_".str_replace(' ','-',$product->getName())."_".date("Y-m-d").".pdf";
$pdf = $exportService->PDF_Recipe($product,$recipe,$user);
$upload = $httpService->uploadPDF($user,$pdf,$filename,"product_recipe/");
$test = json_decode($upload);
return new JsonResponse($test, 200, [], true);
Note that $pdf is generated using Output('','S')
. Then, here is my uploadFile()
function :
public function uploadPDF(User $user,$file,$filename,$folder)
{
$upload = $this->getUploadUrl($user);
$client = HttpClient::create([
"headers"=>[
'Authorization' => $upload["authorizationToken"],
'X-Bz-File-Name' => "oui.pdf",
'X-Bz-Content-Sha1'=> sha1($file),
'Content-Length' => strlen($file),
'Content-Type' => "application/pdf"
]
]);
$response = $client->request('POST',$upload["uploadUrl"].'/b2api/v2/b2_upload_file',[
'body'=>$file
]);
$statusCode = $response->getStatusCode();
$content = $response->getContent();
return $content;
}
I'm 100% sure that my uploadUrl()
function is working. But I'm getting a 400 error. My first struggle is to actually show the Backblaze API response, actually when I try my endpoint in postman I just get a 500 error with that message "HTTP/1.1 400 returned for \"MYUPLOADURL"."
But if I build my request myself in postman, get the upload irl and attach a file, it works well, and when not I have a detailed response with what's wrong (wrong header or anything like that).
How can I make my endpoint to actually show me the real response from Backblaze ? And how to actually manage to send a pdf file as a string ?
Thanks to user that commented, I found that the Symfony's Http Client is set to throw an exception for any response with a status code between 300 and 599. To avoid that and see what's wrong in your request you have to call the
$response->getContent()
or$response->toArray()
with false as an argument.In my case, using
getContent(false)
allowed me to see that I just mis writted the url in my request :)$upload["uploadUrl"].'/b2api/v2/b2_upload_file'
is supposed to be just$upload["uploadUrl"]
because the Backblaze API return the full upload url when asked.Thanks !