I am trying to upload an image in Laravel. Getting the following error:
"message": "Could not move the file \"C:\\xampp\\tmp\\php84AA.tmp\" to \"F:\\bvend\\bvend-web\\public\\uploads/products\\bvend-product-1666274539.jpg\" (move_uploaded_file(): Unable to move "C:\\xampp\\tmp\\php84AA.tmp" to "F:\\bvend\\bvend-web\\public\\uploads/products\\bvend-product-1666274539.jpg").",
"exception": "Symfony\\Component\\HttpFoundation\\File\\Exception\\FileException",
"file": "F:\\bvend\\bvend-web\\vendor\\symfony\\http-foundation\\File\\UploadedFile.php",
"line": 177,
"trace": [ .... ]
My code is given below:
public function uploadImage($image, $image_path)
{
$path = config('global.' . $image_path . '_image_path');
file_exists($image) && unlink($image);
$image_name = 'bvend-' . $image_path . '-' . time() . '.' . $image->getClientOriginalExtension();
$image->move($path, $image_name); // $path: public_path('uploads/products')
return $image_name;
}
I understand its a simple issue but still no clue where it causing issue.
@WahidulAlam Please, try removing
file_exists($image) && unlink($image);
– steven7mwesigwa - https://stackoverflow.com/posts/comments/130904221?noredirect=1@WahidulAlam You're essentially deleting the temporary file/image before its copied or moved.
– steven7mwesigwa - https://stackoverflow.com/posts/comments/130904261?noredirect=1ah this is the catch !! thanks a lot.
– Wahidul Alam - https://stackoverflow.com/posts/comments/130904399?noredirect=1
If you do not want a filename to be automatically assigned to your stored file, you may use the
storeAs
method, which receives the path, the filename, and the (optional) disk as its arguments:
$path = $request->file('avatar')->storeAs( 'avatars', $request->user()->id );
You may also use the
putFileAs
method on theStorage
facade, which will perform the same file storage operation as the example above:
$path = Storage::putFileAs( 'avatars', $request->file('avatar'), $request->user()->id );
public function uploadImage(\Illuminate\Http\UploadedFile $image, $image_path)
{
return $image->storePubliclyAs(
config('global.' . $image_path . '_image_path'),
'bvend-' . $image_path . '-' . time(),
["disk" => "public"]
);
}
Don't forget to create a symbolic link from public/storage
to storage/app/public
. I.e:
php artisan storage:link
.
Once a file has been stored and the symbolic link has been created, you can create a URL to the files using the
asset
helper:
echo asset('storage/file.txt');
$savedPath = $request->file("***REQUEST-INPUT-IMAGE-NAME-HERE***")->storePubliclyAs(
"***IMAGE-PATH-HERE***",
"***CUSTOM-FILENAME-HERE***",
["disk" => "public"]
);