使用 Postman 的 Laravel 文件上传 API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46633582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel file upload API using Postman
提问by Starfish
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
:
通过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--
POST /scotic/public/api/upload HTTP/1.1 主机:127.0.0.1:80 内容类型:multipart/form-data;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW 缓存控制:无缓存邮递员令牌:0caf7349-5c91-e5f1-766f-72a3f1e33900
------WebKitFormBoundary7MA4YWxkTrZu0gW 内容配置:表单数据;名称="上传[]"; filename="banana.png" Content-Type: image/png png 数据在这里.. ------WebKitFormBoundary7MA4YWxkTrZu0gW--
The $files
is empty upon uploading the file. What am i doing wrong?
该$files
是在上传该文件是空的。我究竟做错了什么?
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.
经过一番挖掘,我让我的上传器在没有邮递员的情况下工作,我注意到邮递员中缺少“--边界” Content-Type
。LHS 有效,RHS(邮递员)无效。
Any ideas?
有任何想法吗?
回答by Starfish
The issue was that I was explicitly specifying the Content-Type
in postman.
问题是我明确指定了Content-Type
邮递员。
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 设置的值。只需在 POST 请求中选择 form-data 并发送您的请求以查看它是否有效。