I'm trying to remove a folder with images in it.
here is my method for removing the file
public function deleteCar($id) {
$car = Car::find($id);
$carImages = carImage::where('car_id', $id);
foreach ($carImages as $image) {
//Just for testing purposes.
$image->car_image_path = '/uploads/cars/32/exampleImage.png';
$pathWords = explode('/', $image->car_image_path);
$path = $pathWords[0] . '/' . $pathWords[1] . '/' . $pathWords[2] . '/' . $pathWords[3];
File::deleteDirectory($path);
$image->delete();
}
$car->delete();
return response()->json(['error' => false, 'data' => $id]);
}
What I want to accomplish is to remove the folder and then the model with the correct car_id. That is passed.
The folder does not get removed and neither does the image model.
You have to use public_path to delete directory:
File::deleteDirectory(public_path('uploads/cars/32'));
The method will return true if it succeeds, false if it fails.
Hope it helps
Related
I'm using Laravel 9 and Image Intervetion to resize uploaded images:
public static function resize($file, $fileName)
{
$path = self::route();
foreach (self::size() as $key => $value) {
$resizePath = self::route() . "{$value[0]}x{$value[1]}_" . $fileName;
Image::make($file->getRealPath())
->resize($value[0], $value[1], function ($constraint) {
$constraint->aspectRatio();
})
->save(storage_path($resizePath));
$urlResizeImage[] = ["upf_path" => $resizePath, "upf_dimension" => "{$value[0]}x{$value[1]}"];
}
self::$urlResizeImage = $urlResizeImage;
}
But the line ->save(storage_path($resizePath)); returns this error:
Can't write image data to path
So in the Image Facade of Intervention, there's a #file_put_contents:
public function save($path = null, $quality = null, $format = null)
{
$path = is_null($path) ? $this->basePath() : $path;
// dd($path);
if (is_null($path)) {
throw new NotWritableException(
"Can't write to undefined path."
);
}
if ($format === null) {
$format = pathinfo($path, PATHINFO_EXTENSION);
}
$data = $this->encode($format, $quality);
$saved = #file_put_contents($path, $data);
if ($saved === false) {
throw new NotWritableException(
"Can't write image data to path ({$path})"
);
}
// set new file info
$this->setFileInfoFromPath($path);
return $this;
}
And I tried removing # from #file_put_contents to see what's going wrong here, but then I got this:
file_put_contents(C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/107200x200_1671289517402.jpg): Failed to open stream: No such file or directory
So it basically says that it can not find the $path and when I uncomment dd($path), this is the output:
C:\xampp\htdocs\project\storage\upload/1401/11/images/questions/108200x200_1671289517402.jpg
So what's going wrong here?
How can I properly save the resized images into this directory?
Please I beg you to help me with this because it's been a week that I'm struggling with this error and got headache!
UPDATE #1:
Here is the route():
public static function route()
{
return "upload/" . jdate()->format('Y') . "/" . jdate()->format('m') . "/" . self::$typeFile . "/" . strtolower(self::$catType)."s" . "/" . self::$objId;
}
And I changed it to this:
public static function route()
{
return "upload".DIRECTORY_SEPARATOR.jdate()->format('Y').DIRECTORY_SEPARATOR.jdate()->format('m').DIRECTORY_SEPARATOR.self::$typeFile.DIRECTORY_SEPARATOR.strtolower(self::$catType)."s".DIRECTORY_SEPARATOR.self::$objId;
}
But still the same error occurs :(
I have some problem to delete file when some value deleted.
This is my delete function:
public function delete($id, Adopsi $adopsi)
{
Storage::delete('post/adopsi/' . $adopsi->image_post_adps);
$data = Adopsi::where('id', $id)->delete();
if ($data) {
return redirect()->route('adopsi.index')->with('success', 'Data telah dihapus');
} else {
return redirect()->route('adopsi.index')->with('error', 'Data gagal dihapus');
}
}
This is how I store my image before:
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$request->file('image_post_adps')->storeAs('public/post/adopsi', $imageName);
directory folder where is use to save:
storage/app/public/post/adopsi/..... (there's my file),
I've used Storage::delete() and unlink() but it still isn't working.
Your images are stored at 'public' disk path. But disk is not specified in delete()
Try
Storage::disk('public')->delete('post/adopsi/' . $adopsi->image_post_adps);
First, make sure the file exists by building the path:
First of all, add the File Facade at the top of the controller:
use Illuminate\Support\Facades\File;
You can use public_path() & storage_path():
$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path)) {
File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}
$path = storage_path().'/app/public/post/adopsi/'.$db->image;
if(File::exists($path)) {
File::delete($path);
}
The below worked for me
$destinationPath = storage_path() . '/app/public/images/products';
File::delete($destinationPath . '/' . $product->id . '.' . $fileExtension);
I upload from vue 4-5 images to different folders in laravel.
public function uploadImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$name = $o2order->contactname;
$name2 = str_replace(' ', '_', $name);
$image = $request->file('file');
$imageName = $name2.'.'.time().'.'.$image->extension();
$wwwPath = 'https://api2.api.sk/storage/';
$image->move(storage_path('app/o2/servisne' . '/' . $name2),$imageName);
$imagePath = 'https://api2.api.sk/storage/app/o2/' . ('servisne' . '/' . $name2);
$o2order->servisny = $imagePath;
$o2order->save();
}
This is working fine. In storage/app/o2/servisne_listy/ is folder created and multiple images stored. In sql is written full path to this folder.
I need to show this image or images, sometimes its one sometimes more, not same.
I have this:
public function showImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$servisny = $o2order->servisny;
return response()->json(['servisny' => $servisny], 200);
}
Its shows only the path from sql, but i need path to every file which is in this directory.
Thanks
May be this help you
$path = storage_path('app/o2/servisne');
$files = File::files($path)
I have successfully uploaded a file into Google Drive. However, I'm still not sure on how to upload it into a folder. I need to upload it into a folder structure which looks like this:
Stats
ACLLeauge
ACLSydney
Sorted
Unsorted
{Username}
{FileHere}
The {Username} field is a variable that I will pass through. The {FileHere} field is where the image needs to go. Here is my current code:
public function __construct()
{
$this->instance = new \Google_Client();
$this->instance->setApplicationName('DPStatsBot');
$this->instance->setDeveloperKey(Config::getInstance()->getDriveDeveloperKey());
$this->instance->setAuthConfigFile(Config::getInstance()->getClientSecret());
$this->instance->addScope('https://www.googleapis.com/auth/drive');
if(!file_exists(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile())) {
Printer::write('Please navigate to this URL and authenticate with Google: ' . PHP_EOL . $this->instance->createAuthUrl());
Printer::raw('Authentication Code: ');
$code = trim(fgets(STDIN));
$token = $this->instance->authenticate($code);
file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $token);
Printer::write('Saved auth token');
$this->instance->setAccessToken($token);
}
else
{
$this->instance->setAccessToken(file_get_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile()));
}
if($this->instance->isAccessTokenExpired())
{
$this->instance->refreshToken($this->instance->getRefreshToken());
file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $this->instance->getAccessToken());
}
$this->drive_instance = new \Google_Service_Drive($this->instance);
}
public function upload($image, $dpname)
{
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($dpname . '_' . RandomString::string() . '.jpg');
$upload = $this->drive_instance->files->insert($file,
[
'data' => $image,
'mimeType' => 'image/jpg',
'uploadType' => 'media'
]);
return $upload;
}
If anyone has a suggestion please tell me!
Thanks
For this you have insert the folders in the order you wanted. So add the Stats under the Drive root folder and then add all the folders in the order you needed. For adding a folder, you need to give mimeType as 'application/vnd.google-apps.folder'. Check this link for more mimeType values. Here is an external referring link on how to insert a folder in Drive.
After adding all the required folders you can now insert the actual file under the {Username} folder. You can also refer to this page on how to insert a file in Drive.
Hope that helps!
So I am trying to use rename function in php.
On the first try, if the destination folder is empty or does not contain any directories with the same name as the source folder the rename function works perfectly. However, if there is same directory name it fails. What I want is just to overwrite it and I thought rename() would suffice.
Here is my code:
/**
* Move temp folders to their permanent places
*
* $module_folder = example (violator, pnp, etc)
* $folders = name of folders within module_folder
**/
public function move_temp_to_permanent($module_folder, $folders){
$bool = false;
$module_folder_path = realpath(APPPATH . '../public/resources/temps/' . $module_folder);
$module_folder_destination_path = $_SERVER['DOCUMENT_ROOT'] . '/ssmis/public/resources/photos/' . $module_folder . '/';
foreach($folders as $folder){
$bool = rename($module_folder_path . '/' . $folder, $module_folder_destination_path . $folder);
}
return $bool;
}
The code above gives me an error saying:
Message:
rename(C:\xampp\htdocs\ssmis\public\resources\temps\violator/SJ-VIOL-2015-0002,C:/xampp/htdocs/ssmis/public/resources/photos/violator/SJ-VIOL-2015-0002):
Access is denied. (code: 5)
I am using CodeIgniter as framework.
Thank you very much!
If it is on Windows, this can be read in contributions:
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5. If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state. You can do something like this instead:
function rename_win($oldfile,$newfile) {
if (!rename($oldfile,$newfile)) {
if (copy ($oldfile,$newfile)) {
unlink($oldfile);
return TRUE;
}
return FALSE;
}
return TRUE;
}
Link.
You are adding extra / in path make this like
/**
* Move temp folders to their permanent places
*
* $module_folder = example (violator, pnp, etc)
* $folders = name of folders within module_folder
**/
public function move_temp_to_permanent($module_folder, $folders){
$bool = false;
$module_folder_path = realpath(APPPATH . '../public/resources/temps/' . $module_folder);
$module_folder_destination_path = $_SERVER['DOCUMENT_ROOT'] . '/ssmis/public/resources/photos/' . $module_folder . '/';
foreach($folders as $folder){
$bool = rename($module_folder_path . $folder, $module_folder_destination_path . $folder);
}
return $bool;
}
you can also echo the path you prepared so you can check its right or not