我想编写一个文件下载测试,为此,我首先上传文件,然后调用API下载上传的文件,上传成功,但下载始终失败,并显示The file "/var/www/public/uploads/dWwECsHQpcwJuYTn6uaLmPxk4uINOeYOZYiZ86Oc.jpeg" does not exist
。
以下是我的测试功能内容:
Storage::fake('public');
$business = factory(Business::class)->create(['owner_id' => $this->businessUser->id]);
$response = $this->jsonAs($this->businessUser,'POST', '/api/file/business', [
'file' => $file = UploadedFile::fake()->create('invalid file.jpg'),
'attachable_id' => $business->id,
'attachable_type' => 'businesses'
]);
$response->assertJson(['name' => $file->hashName()]);
Storage::disk('public')->assertExists('uploads/' . $file->hashName());
$uploadRes = $response->decodeResponseJson();
$response = $this->jsonAs($this->businessUser, 'GET', '/api/file/'. $uploadRes['id'] . '/business/' .$business->id);
// This assertion always fails
// If I dd above response, shows this message 'The file "/var/www/public/uploads/dWwECsHQpcwJuYTn6uaLmPxk4uINOeYOZYiZ86Oc.jpeg" does not exist'
$this->assertTrue($response->headers->get('content-type') == $file->getClientMimeType());
$this->assertTrue($response->headers->get('content-disposition') == 'attachment; filename="' . $uploadRes['original_filename'] . '"');
$response->assertStatus(200);
以下是我的下载功能内容:
$attachment = Attachment::where('id', $id)->firstOrFail();
$path = public_path(). '/uploads/' . $attachment->name;
return response()->download($path, $attachment->original_filename, ['Content-Type' => $attachment->mime]);
答案 0 :(得分:1)
确保文件位于 public / upload 目录中,并且可以使用url()
函数为公共目录文件生成链接。
EX:
$attachment = Attachment::where('id', $id)->firstOrFail();
$path = url('uploads/' . $attachment->name);
return response()->download($path, $attachment->original_filename, ['Content-Type' => $attachment->mime]);
答案 1 :(得分:0)
在下载实现中,我注意到使用了public_path
函数。
public_path
函数从服务容器解析,可能从public
磁盘配置的实际路径创建了新路径。
Storage::fake
正在设置磁盘路径并返回FilesystemAdapter
,并且您要确保这是测试规范生命周期中使用的实例。
我建议尝试通过Storage
门面使用FilesystemAdapter中的path方法来构造下载实现中的路径,而不是public_path
帮助函数。例如:
Storage::disk('public')->path('uploads/'.$attachment->name);