How to send file as form data using laravel GuzzleHttpClient
?
My upload.blade.php
:
<!-- is enctype="multipart/form-data required here? --> <form action="/upload-order" method="post" enctype="multipart/form-data"> {{csrf_field()}} <p><input type="file" name="work_order" id="work_order"></p> <p><input type="submit" value="Upload Work Order"></p> </form>
My web routing:
Route::post('/orders-mgmt/upload-order', [ 'uses' => 'UploadController@uploadOrder' ])->name('upload-order');
My UploadController.php
:
public static function uploadOrder(Request $request) { if (!($request->hasFile('work_order'))) { $message = "No file is selected."; return redirect('/orders-mgmt/requests')->with('warnmessage', $message); } $file= $request->file('work_order'); $file_path = $file->getPathname(); $file_uploaded_name = $file->getClientOriginalName(); $resBody = (new UploadService($env))->uploadWorkOrderCSV($file_path, $file_uploaded_name); ... }
My UploadService.php
public function uploadWorkOrderCSV($file_path, $file_uploaded_name) { return json_decode($this->client->request( 'POST', 'v1/provision/upload-order', [ 'multipart' => [ 'name' => 'work_order', 'contents' => fopen($file_path, 'r'), 'filename' => $file_uploaded_name ] ] )->getBody()); }
I got the following error but I think the way I manipulate the form data is already wrong.
Type error: Argument 2 passed to GuzzleHttpPsr7MultipartStream::addElement() must be of the type array, string given, called in
The curl command below works for uploading file, how do I actually build the same request in my UploadService
?
curl -X POST http://localhost:5000/v1/provision/upload-order -F 'work_order=@/C:/Users/kai/Desktop/Local/work_order.csv'
Advertisement
Answer
multipart values have to be in a nested array
public function uploadWorkOrderCSV($file_path, $file_uploaded_name) { return json_decode($this->client->request( 'POST', 'v1/provision/upload-order', [ 'multipart' => [ [ 'Content-type' => 'multipart/form-data', 'name' => 'work_order', 'contents' => fopen($file_path, 'r'), 'filename' => $file_uploaded_name ] ] ] )->getBody()); }