Skip to content

Commit 15eb9df

Browse files
committed
Test downloading a private file
1 parent fe489a5 commit 15eb9df

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

app/Http/Controllers/MediaUploaderController.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,28 @@ public function resize()
7171

7272
return ['path' => $path];
7373
}
74+
75+
/**
76+
* Not this method is coupled with download() method
77+
* because it needs a file for downloading
78+
*
79+
* @return array
80+
*/
81+
public function uploadPrivate()
82+
{
83+
$privateFilename = 'private-file.pdf';
84+
85+
$path = \request()->file('file')->storeAs('private', $privateFilename, 'local');
86+
87+
return ['path' => $path];
88+
}
89+
90+
public function download($filename)
91+
{
92+
// Retrieve the private file. Based on user subscription or role, for example.
93+
94+
$privateFilepath = Storage::disk('local')->path('private/private-file.pdf');
95+
96+
return response()->download($privateFilepath, $filename);
97+
}
7498
}

routes/web.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,9 @@
5151
Route::post('/upload/multiple-files', 'uploadMultipleFiles')->name('upload.multiple');
5252

5353
Route::post('/upload/resize', 'resize')->name('upload.resize');
54+
55+
Route::post('/upload/private', 'uploadPrivate')->name('upload.private');
56+
57+
Route::get('/upload/download/{filename}', 'download')->name('upload.download');
5458
});
5559
});

tests/Feature/UploadModuleTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,25 @@ public function it_can_resize_uploaded_image()
103103
$this->assertEquals(300, $image->width());
104104
$this->assertEquals(200, $image->height());
105105
}
106+
107+
/** @test */
108+
public function it_can_download_a_private_file()
109+
{
110+
$this->actingAs(User::factory()->create());
111+
112+
Storage::fake('local');
113+
114+
$response1 = $this->post(route('upload.private'), [
115+
'file' => $file = UploadedFile::fake()->create('private-file.pdf', 1024, 'application/pdf'),
116+
]);
117+
118+
Storage::disk('local')->assertExists($response1->json('path'));
119+
120+
// This name will determine the filename that is seen by the user downloading the file
121+
$filename = 'download-private-file.pdf';
122+
123+
$response2 = $this->get(route('upload.download', $filename));
124+
$response2->assertStatus(200);
125+
$response2->assertDownload($filename);
126+
}
106127
}

0 commit comments

Comments
 (0)