使用Postman的Laravel文件上传API [英] Laravel file upload API using Postman

查看:796
本文介绍了使用Postman的Laravel文件上传API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中包含以下代码:

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

通过routes中的api.php调用哪个:

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

我正在使用邮递员来测试我的应用程序.

标题:

身体:

原始:

POST/scotic/public/api/upload HTTP/1.1主机:127.0.0.1:80 内容类型:多部分/表单数据; boundary = ---- WebKitFormBoundary7MA4YWxkTrZu0gW缓存控件:无缓存 邮递员令牌:0caf7349-5c91-e5f1-766f-72a3f1e33900

------ WebKitFormBoundary7MA4YWxkTrZu0gW内容处置:form-data; name ="uploads []"; filename ="banana.png"内容类型: image/png png数据在这里. ------ WebKitFormBoundary7MA4YWxkTrZu0gW-

$files在上传文件时为空.我究竟做错了什么?

经过一番挖掘,我使上载程序在没有邮递员的情况下工作,我注意到邮递员Content-Type中缺少'--boundary'. LHS有效,RHS(邮递员)无效.

有什么想法吗?

解决方案

问题是我在邮递员中明确指定了Content-Type.

根据此帖子的答案之一:

不需要手动添加内容类型标头.您将覆盖Postman设置的值.只需在POST请求中选择表单数据,然后发送您的请求以查看其是否有效.

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:

Body:

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.

Any ideas?

解决方案

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.

这篇关于使用Postman的Laravel文件上传API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆