Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel file upload API using Postman

I have the following code in my controller:

    public function upload(Request $request)
    {
       $files = $request->file('uploads');
       if(!empty($files)) {
           foreach($files as $file) {
               Storage::put($file-getClientOriginalName(),file_get_contents($file));
        }
    }

Which is called via an api.php in routes:

Route::post('/upload', [ 'uses' => 'UploadController@upload' ]);

I am using postman to test my application.

Header:

enter image description here

Body:

enter image description here

Raw:

POST /scotic/public/api/upload HTTP/1.1 Host: 127.0.0.1:80 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW Cache-Control: no-cache Postman-Token: 0caf7349-5c91-e5f1-766f-72a3f1e33900

------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="uploads[]"; filename="banana.png" Content-Type: image/png png data goes here.. ------WebKitFormBoundary7MA4YWxkTrZu0gW--

The $files is empty upon uploading the file. What am i doing wrong?

After a bit of digging, I got my uploader working without postman, I noticed that the '--boundary' was missing from the Content-Type in postman. The LHS works, RHS(postman) does not work.

enter image description here

Any ideas?

like image 431
Starfish Avatar asked Oct 08 '17 16:10

Starfish


People also ask

How do I upload a file in Laravel API?

Begin creating a new file fake. Store the uploaded file on a filesystem disk. Store the uploaded file on a filesystem disk with public visibility. Store the uploaded file on a filesystem disk with public visibility.

How do I upload files in Laravel storage?

To upload files to storage in Laravel, use MAMP or XAMPP as a local web server, define a database name in MySQL, and add the correct configuration in the . env file.


1 Answers

The issue was that I was explicitly specifying the Content-Type in postman.

According to one of the answers from this post:

There is no need to add a content-type header manually. You are overriding the value set by Postman. Just select form-data in POST request and send your request to see if it works.

like image 86
Starfish Avatar answered Oct 19 '22 20:10

Starfish