Php send file to api

Laravel 7 File Upload Via API Example From Scratch

Laravel 7 file upload via API using postman example tutorial. Here, you will learn how to upload files via API using postman in laravel app.

As well as you can upload images, files via API using postman in laravel apps and also you can upload images/files via api using ajax in laravel apps.

If you work with laravel apis and want to upload files or images using postman or ajax. And also want to validate files or images before uploading to server via API or ajax in laravel.

So this tutorial will guide you step by step on how to upload file via API using postman and ajax in laravel with validation.

Laravel Uploading Files Via API Using Postman Example

Follow the below given following steps and upload file via API using postman with validation in laravel app:

  • Step 1: Install Laravel New App
  • Step 2: Add Database Credentials
  • Step 3: Generate Migration & Model
  • Step 4: Create Routes For File
  • Step 5: Generate Controller by Artisan
  • Step 6: Run Development Server
  • Step 7: Laravel Upload File Via Api Using PostMan
Читайте также:  Python install pip surprise

Step 1: Install Laravel New App

First of all, open your terminal and run the following command to install or download laravel fresh application setup for uploading files via laravel api:

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

Step 2: Add Database Credentials

Next, Navigate to your downloaded laravel app root directory and open .env file. Then add your database details in .env file, as follow:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here

Step 3: Generate Migration & Model

In this step, open a command prompt and run the following command:

php artisan make:model Documents -m

This command will create one model name file and as well as one migration file for the Documents table.

Then Navigate to database/migrations folder and open create_documents_table.php. Then update the following code into create_documents_table.php:

increments('id'); $table->string('title'); $table->integer('user_id'); $table->timestamps(); >); > /** * Reverse the migrations. * * @return void */ public function down() < Schema::dropIfExists('documents'); >>

After that, run the following command to migrate the table into your select database:

Step 4: Create Route For File

In this step, Navigate to the app/routes folder and open api.php file. Then update the following routes into your api.php file:

Step 5: Generate Controller by Artisan

In this step, open your terminal and run the following command:

php artisan make:controller Api\DocumentController

Note that, This command will create a controller named DocumentController.php file.

Now app/controllers/Api folder and open DocumentController.php. Then update the following file uploading methods into your DocumentController.php file:

all(), [ 'user_id' => 'required', 'file' => 'required|mimes:doc,docx,pdf,txt|max:2048', ]); if ($validator->fails()) < return response()->json(['error'=>$validator->errors()], 401); > if ($files = $request->file('file')) < //store file into document folder $file = $request->file->store('public/documents'); //store your file into database $document = new Document(); $document->title = $file; $document->user_id = $request->user_id; $document->save(); return response()->json([ "success" => true, "message" => "File successfully uploaded", "file" => $file ]); > > >

If you want to upload images via api instead of files in laravel. So you can change in validation rules on the controller file, as follow:

'file' => 'required|mimes:png,jpg|max:2048',

Step 6: Run Development Server

In this step, run the following command to start the development server:

Step 7: Laravel Upload File Via Api Using PostMan

Finally, uploading files via laravel APIs using postman app. So start postman app and use the following URL to upload files via api in laravel app:

http://localhost:8000/store-file

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this upload file using rest API laravel example tutorial, you have learned how to upload a file using rest api laravel apps using postman.

If you have any questions or thoughts to share, use the comment form below to reach us.

Author Admin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

2 replies to Laravel 7 File Upload Via API Example From Scratch

hi, could make some tutorial about LARAVEL7 use ‘SUMMER NOTE’ with drag&drop multiple image upload ?, thanks

Источник

Php send file to api

I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)

Anyways, here is a fuller example than the sparce one in the documentation above:

foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;

$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);

if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>

Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;

$request = ServerRequestFactory :: fromGlobals ();

if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>

$uploaded_files = $request -> getUploadedFiles ();

if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>

$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];

if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>

$file -> moveTo ( ‘/path/to/new/file’ );

The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.

Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)

Multi-files with HTML array feature —

Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)

[type] => Array
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

function normalize_files_array ( $files = [])

foreach( $files as $index => $file )

if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>

foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>

?>

The following is the output from the above method.

Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)

Источник

How can the PHP send a file to Java api?

I am currently working in a project that is to build a online judging system like codeforces. That is where someone can upload a file for a programming solution and our system will compile the code and generate the output and finally send the result that the solution is correct or not. The front end is going to build in PHP and the compile engine will be in Java Rest api. This will take a http request, where the request containing which file to compile. The file is like A.cpp that is going to be compiled by the java api and response as a result(right/wrong). Now my question is about the file that is send from PHP to Java api. How can the PHP send a file to Java api ? Will there be a file server needed ? Or do I need a file server at all ? If I need a file server what is the benefit I will get ? Actually I am not getting the point what is purpose of a file server. Thank you.

You store the file and call the API with the path as parameter would be one simple solution. Or you store the file in a folder that gets scanned by the API at some time interval. Or a million other ways. Also: Do you intend to run that code on your server? Normally such systems would run it inside a VM or container for security reasons I think. (Also: A file server is a server dedicated to handle files. You would need and use one if you have a lot of files and file handling becomes a bottle neck. Unless you have a very high load on your system you won’t have to worry about this)

@thorstenmüller Thanks for reply. What do you actually mean by running code within a VM or container. and what type of security measure it will ensure.

You would have a virtual machine, setup with everything necessary to compile and run the code. You clon that vm and run the code inside it. Now if the user has some malicious code that maybe tries to format your harddrive, delete files, blocks system resources or whatever else it will be limited to this vm which you delete after you got the output anyway.

It’s called sandboxing. One example: github.com/edx/codejail (there are other variations on this, using LXC containers or similar instead of AppArmor)

1 Answer 1

How can the PHP send a file to Java api?

This can be done in several ways: HTTP post, a data stream etc.

Will there be a file server needed ? Or do I need a file server at all?

If I need a file server what is the benefit I will get ?

The benefits of a file server is sharing storage resources. It’s the same as having a network printer instead of everyone having a cheap desktop printer. With one file server, the PHP program could upload the source file to the file server and them send only the name of the file in a message to the Java API. The result or the process could be stored in the file server and you can download it with another API call. This actually makes the process to be asynchronous. And asynchronous processes are easier to debug and schedule for bulk processing.

Another benefit of it is that in can be managed by a team that takes care of backups, retention times, redundancy, disaster recovery, etc.

EDIT. Why asynchronous processes are easier to debug?

  • The two layers don’t have to be up and running in order to test one of them. For example for testing the PHP code that uploads the file to the file server, the Java API layer needs not to be up. To test the Java API you don’t even have to mock the PHP call. You just put a file in the server and test the Java method that reads the file and compiles it.
  • Basically it’s easier to debug and test a bulk process that takes a bulk of files and processes it.
  • I’ll give you an example: for a phone call (a synchronous communication) to go through, there must be a person in the receiving end to pick up the call. On the other hand when you send an email (an asynchronous communication), the recipient needs not be connected to the internet, but as soon as he/she gets online he will receive a notificationo an email message in his/her inbox. You can test the sending part and the receiving part separatelly with no mocking.
  • Also, less error handling code must be written, meaning less code to test and debug.

Источник

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