Laravel 文件上传 API 使用 Postman

编程入门 行业动态 更新时间:2024-10-28 06:27:53
本文介绍了Laravel 文件上传 API 使用 Postman的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的控制器中有以下代码:

公开函数上传(Request $request){$files = $request->file('uploads');if(!empty($files)) {foreach($files 作为 $file) {存储::put($file-getClientOriginalName(),file_get_contents($file));}}

通过 routes 中的 api.php 调用:

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

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

标题:

主体:

原始:

POST/stic/public/api/upload HTTP/1.1 主机:127.0.0.1:80内容类型:multipart/form-data;边界=----WebKitFormBoundary7MA4YWxkTrZu0gW 缓存控制:无缓存邮递员令牌:0caf7349-5c91-e5f1-766f-72a3f1e33900

------WebKitFormBoundary7MA4YWxkTrZu0gW 内容配置:表单数据;名称="上传[]";文件名="banana.png" 内容类型:image/png png 数据放在这里..------WebKitFormBoundary7MA4YWxkTrZu0gW--

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

经过一番挖掘,我让我的上传器在没有邮递员的情况下工作,我注意到邮递员的 Content-Type 中缺少--boundary".LHS 工作,RHS(邮递员)不工作.

有什么想法吗?

解决方案

问题是我在 postman 中明确指定了 Content-Type.

根据此post 的答案之一::p>

无需手动添加内容类型标头.您正在覆盖 Postman 设置的值.只需在 POST 请求中选择 form-data 并发送您的请求以查看它是否有效.

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.

更多推荐

Laravel 文件上传 API 使用 Postman

本文发布于:2023-10-29 09:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539338.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件上传   Laravel   Postman   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!