how to inject a file into http request

血红的双手。 提交于 2020-01-03 04:54:08

问题


i have a test case:

$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>Storage::get('file/file.xlsx')]);
    $response->assertJsonFragment(['a'=>'b']);

my controller:

public function import(Request $request, Unit $unit)
{

    $this->validate($request, [
        'file' => 'file|required_without:rows',
        'rows' => 'array|required_without:file',
        'dry_run' => 'boolean',
    ]);
    if ($request->has('rows')) {
        //
    } else {
        $results = $request->file('file');
    }

    return "ok";
}

but i think my test case is wrong,because when i dd($reuqest->file('file')) in my controller, it return null. So, how can i request file into my controller. please help


回答1:


You can use UploadFile like this:

$fileName= 'file.png';
$filePath=sys_get_temp_dir().'/'.$fileName;
$mimeTypeFile=mime_content_type($filePath);
$file=new UploadedFile($filePath, $fileName, $mimeTypeFile, filesize('$filePath'), null, true)
$response = $this->postJson('api/unit/'.$unit->id.'/import',['file' =>$file]);
$response->assertJsonFragment(['a'=>'b']);

with null is The error constant of the upload, true is test mode more detail for Symfony UploadedFile, read this




回答2:


As mentioned in this https://laravel.com/docs/5.4/http-tests#testing-file-uploads.

Try something like this. Import use Illuminate\Http\UploadedFile;

UploadedFile::fake()->create('file.xlsx', $size);
Storage::disk('file')->assertExists('file.xlsx');


来源:https://stackoverflow.com/questions/52775833/how-to-inject-a-file-into-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!