Level 75
@giorgiovski Use
$path = public_path('storage/profile_pictures/'.$fileNameToStore);
Image::make($request->file('profile_picture'))->fit(250, 250)->save($path);
1 like
I wrote a test for testing the uploaded image. When I'm testing the API with Postman and Insomnia it works well. But the test fail because the intervention image returns an error. If I switch from intervention image to normal save it works. But I want to use it for resizing images.
This is the line which returns errors:
Image::make($request->file('profile_picture'))->fit(250, 250)->save($path.$fileNameToStore);
The error:
Can't write image data to path (storage/profile_pictures/avatarForTesting_1588586805.jpg)
Test
public function testIfUsersCanUploadFirstAvatar(){
$this->withoutExceptionHandling();
// Create user
$user = factory(User::class)->create();
$trainee = factory(Trainee::class)->create(['trainee_id' => $user->id]);
// Login user
$this->actingAs($user);
// Update profile with filled file upload request
$response = $this->json('POST','http://api.'.env('APP_URL').'/profile/update/avatar/'.$user->id,
[
'profile_picture' => UploadedFile::fake()->image('avatarForTesting.jpg', 200)
]);
// Check if the avatar path is updated regarding uploaded picture
$getImageName = User::find($user->id);
$this->assertEquals(substr($getImageName->profile_picture, 0, -15), 'avatarForTesting');
}
Upload Image
public function saveProfilePicture(Request $request, $userId)
{
$request->validate([
'profile_picture' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5120',
],
['Please select an avatar before trying to upload',]
);
//Users avatar uploading
if ($request->hasFile('profile_picture')) {
// Get filename with the extension
$filenameWithExt = $request->file('profile_picture')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('profile_picture')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
//Reduce the size of the image and upload image
$path = 'storage/profile_pictures/';
// $path = $request->file('profile_picture')->storeAs('storage/profile_pictures', $fileNameToStore);
Image::make($request->file('profile_picture'))->fit(250, 250)->save($path.$fileNameToStore);
} else {
$fileNameToStore = 'no_profile_picture.jpg';
}
Thank you in advance.
@giorgiovski Use
$path = public_path('storage/profile_pictures/'.$fileNameToStore);
Image::make($request->file('profile_picture'))->fit(250, 250)->save($path);
Please or to participate in this conversation.