Laravel file upload API using Postman
Asked Answered
W

1

12

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?

Winn answered 8/10, 2017 at 16:48 Comment(2)
Try implementing via base64 data.Willner
I compared the postman with web-browser it seems that '--boundary' is missing in postman - any idea how to fix it?Winn
W
12

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.

Winn answered 12/10, 2017 at 19:18 Comment(2)
Yes, I just removed the Content-Type from the header in the input and it worked. I would suggest you to use Wireshark to capture the TCP packets and troubleshoot.Winn
Any chance you used guzzle later on to make the actual post ? I've got the same case as you with a post including file and data. It works with Postman thanks to your post but I can't get it to work with the code. Using GuzzleHttp to make the requestSelfconsequence

© 2022 - 2024 — McMap. All rights reserved.