Php rest api upload file

PHP REST API Single File Upload

I am going to show you how to upload single file using REST API in PHP language. The full form of REST is Representational State Transfer. I will use POST method to upload the file. The REST API will get the file content from the client and will store the file content to a specified destination. The destination could be any location that you specify in the server.

Prerequisites

Project Directory

It’s assumed that you have setup PHP in your system.

Now I will create a project root directory called php-rest-api-single-file-upload anywhere in your system. I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project’s root directory.

REST File Upload Code

In the header I have configured origin from where the request is allowed, so here I allow from any origin. I am using HTTP method POST for uploading file. I have also allowed several other attributes in the HTTP header.

I am only allowing a file size less than 5MB to be uploaded in the server. You can change the file size according to your needs.

The name of the key of the input file is sendfile in the client request. The file will be uploaded into the upload folder of the server.

Читайте также:  Клиент сервер сокет python

I allow only certain types of files to be uploaded and you can change this to any file types you want to upload.

The appropriate message is shown to the client upon file upload success or failure.

 "please select a file", "status" => false)); > else < $upload_path = 'upload/'; // set upload folder path $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION)); // get file extension // valid file extensions $valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'pdf', 'docx', 'txt'); // allow valid file formats if(in_array($fileExt, $valid_extensions)) < //check file does not exist in the upload folder path if(!file_exists($upload_path . $fileName)) < // check file size '5MB' if($fileSize < 5000000) < if(move_uploaded_file($tempPath, $upload_path . $fileName)) < // move file from system temporary path to the upload folder path echo json_encode(array("message" =>"File Uploaded Successfully", "status" => true)); > else < echo json_encode(array("message" =>"File couldn't be uploaded", "status" => false)); > > else < echo json_encode(array("message" =>"Sorry, your file is too large, please upload 5 MB size", "status" => false)); > > else < echo json_encode(array("message" =>"Sorry, file already exists check upload folder", "status" => false)); > > else < echo json_encode(array("message" =>"Sorry, only JPG, JPEG, PNG, GIF, PDF, DOCX & TEXT files are allowed", "status" => false)); > > 

REST Client

You need REST client to test the file upload functionality. You can use any REST client tool such as Postman, Talend, SOAP UI, etc. I am not using any REST client tool, so I am writing REST client program in PHP to upload file. I am using CURL to upload file.

 curl_file_create('C:\java-math-round-issue.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Word-doc.docx')); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://localhost/php-rest-api-file-upload.php'); curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data')); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); 

The above client program will upload the file in the destination.

Make sure you run the server side REST API for upload before you execute the client program.

Источник

Upload File From Frontend Server To REST API Server In PHP
Upload Files From Frontend Server To API Server | Micro Service Architecture

In this article I will show you how to upload file from Frontend ie your customer facing web app to REST API.

Sometimes you might work with Micro Service architecture where you will have an API Server, Frontend Server, Database Server, where every piece of code resides in different servers. Then the main advantage of using this is the flexibility of using different technologies.

Let me show you how to upload the file from frontend to api server.

We will cover the following topics

  1. Setting Up Frontend & Backend Laravel App
  2. Staring Frontend & Backend Servers
  3. Download GuzzleHttp On Frontend App
  4. Frontend Form Creation
  5. Handle Form Submission In Frontend Controller
  6. Handling Request Data In API

Prerequisites

You should have a working laravel application or install fresh one with the following command

Frontend Laravel App

composer create-project --prefer-dist laravel/laravel frontend 

API Laravel APP

composer create-project --prefer-dist laravel/laravel backend 

1) Staring Frontend & Backend Servers

Now we have downloaded Laravel app and have setup both frontend and backend. Lets start the server the servers individually with the following command

Frontend Project

php artisan serve --port=8080 

Backend Project

php artisan serve --port=8081 

Accessing Frontend & Backend

As we saw above the frontend project can be access from web with the following command

Backend is nothing but the REST API project which we will internally consume from frontend project. Lets run the internal server so that we can access it from frontend with the following URL

2) Download GuzzleHttp On Frontend App

To make cross web requests you can use CURL . Since we will already we have Guzzle which is around the same and with advanced features we will use it. Use the following command to download the Guzzle Http composer package on frontend.

composer require guzzlehttp/guzzle

3) Frontend Form Creation

web.php

Route::get('/upload_files', 'TestingController@create'); Route::post('upload_files', 'TestingController@store');

Lets start form creation to upload the file. Make sure to observe enctype=»multipart/form-data»

Upload Form

form action=">" method="post" enctype="multipart/form-data"> @csrf p>input type="file" name="uploaded_file" id="file">p> p>input type="submit" value="Upload File">p> form> 

This is your normal form. Which has file field to upload any type of file.

Following is my routes to display the form field and where to send after submitting the form.

4) Handle Form Submission In Frontend Controller

As we saw routes from web.php that our form will now point to TestingController to method store we can can access the form fields with the following code

We can access the file uploads with the following code in the controller

$file = request('uploaded_file'); $file_path = $file->getPathname(); $file_mime = $file->getMimeType('image'); $file_uploaded_name = $file->getClientOriginalName();

To start using Guzzle we can access with the following

$client = new \GuzzleHttp\Client(); /** Since we are using POST request I will demo the same */ $client->request("POST", $url_path_to_send_request, form_fields_or_multipart_fields);

Let me show you the actual code how to access it. I have explained everything in the code itself with comments.

/** REST API path where we want to send the data */ $uploadFileUrl = 'http://127.0.0.1:8081/api/upload-file'; /** Start Guzzle Client */ $client = new \GuzzleHttp\Client(); try < /** Guzzle CURL POST request */ $response = $client->request("POST", $uploadFileUrl, [ /** Multipart form data is your actual file upload form */ 'multipart' => [ [ /** This is the actual fields name that you will use to access in API */ 'name' => 'uploaded_file', 'filename' => $file_uploaded_name, 'Mime-Type'=> $file_mime, /** This is the main line, we are reading from file temporary uploaded location */ 'contents' => fopen($file_path, 'r'), ], /** Other form fields here, as we can't send form_fields with multipart same time */ [ /** This is the form filed that we will use to acess in API */ 'name' => 'form-data', /** We need to use json_encode to send the encoded data */ 'contents' => json_encode( [ 'first_name' => 'Channaveer', 'last_name' => 'Hakari' ] ) ] ] ]); > catch (Exception $e) < /** This is generic exception, you can even handle ServerException & ClientException of guzzle */ > /** Check the response status code */ $code = $response->getStatusCode(); /** Get the response body return by API */ $response = $response->getBody(); /** 2nd parameter is true because I want in array format */ $responseData = json_decode($response, true); /** Most of the time it will be JSON data so better decode the JSON to Array as follows */ echo '
'; print_r($responseData);

5) Handling Request Data In API

API's api.php routes

Route::post('upload-file', 'UploadsController@uploadFile');

Now lets handle the data that we got from Frontend and upload to specific path and return some code

UploadsController

public function uploadFile(Request $request) < /** Other code like validation and some other stuff here */ /** Following is the code which you will use to handle the file upload */ if ($request->hasFile('uploaded_file')) < /** Make sure you will properly validate your file before uploading here */ /** Get the file data here */ $file = $request->file('uploaded_file'); /** Generate random unique_name for file */ $fileName = time().md5(time()).'.'.$file->getClientOriginalExtension(); $file->move(public_path().'/uploads/test', $fileName); /** Return data */ return response()->json([ 'status' => 'success', 'message' => 'Your success message', 'data' => [ 'uploadedFileName' => $fileName ] ], 200); > >

Caution

Make sure to handle the following in the above code

  1. Post Data Validation
  2. File Validations Like MIME Type, File Size, If Any Error In Form Upload
  3. Save New File Name In Database
  4. Proper return Data

Conclusion

Hope you found it useful. Kindly share with your friends.

Источник

Оцените статью