简体   繁体   English

在Laravel中,在自定义http请求中传递文件

[英]In Laravel, passing a file in a custom http request

I'm trying to test a controller method that accepts a file in its request. 我正在尝试测试在其请求中接受文件的控制器方法。

In my test I have the following line: 在我的测试中,我有以下内容:

$this->call('POST', 'image/upload', ['image' => $image]);

Where $image is a Symfony\\Component\\HttpFoundation\\File\\UploadedFile instance. 其中$imageSymfony\\Component\\HttpFoundation\\File\\UploadedFile实例。

In the controller method I'm testing it accepts the request object and retrieves the uploaded file via: 在我测试的控制器方法中,它接受请求对象并通过以下方式检索上传的文件:

$image = $request->file('image');

However the file is only available via $request->get('image'); 但是该文件只能通过$request->get('image'); when the action is called via my custom http request above. 通过上面的自定义http请求调用该操作时。 (An ordinary request from the browser produces the expected behaviour). (来自浏览器的普通请求会产生预期的行为)。

How can I pass the file into the file part of the request object? 如何将文件传递到请求对象的file部分?

You are passing the file in as part of the $_POST global where you should be setting it in the $_FILE global. 您正在将文件作为$_POST全局的一部分传入,应在$_FILE全局中设置它。

To do that, I believe you pass the file in as the 5th parameter. 为此,我相信您将文件作为第5个参数传入。

$this->call('POST', 'image/upload', [], [], ['image' => $image]);

Then you should be able to grab it using $request->file('image') 然后,您应该可以使用$request->file('image')来抓取它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM