KBE
KBE

Reputation: 21

Upload multiple images, display a list with filename and new filename, and handle renaming on both source and destination directories(Laravel + AJAX)?

I’m working on a Laravel project where I need to implement a multiple image upload feature with the following requirements:

  1. Shared Directories:

The source folder and destination folder are network-shared paths. After uploading the files to the destination folder with the new names, the files should be renamed in the source folder as well.

My Problem:

However, I’m struggling with:

Route code:

Route::post('/upload-images', 'ImageController@uploadImages');

Controller code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImageController extends Controller
{
    public function uploadImages(Request $request)
    {
        $images = $request->file('images');
        $newFilenames = $request->input('newFilenames');
        
        $sourcePath = '\\\\172.20.1.201\\source\\';
        $destinationPath = '\\\\172.20.1.201\\destination\\';

        foreach ($images as $index => $image) {
            $originalName = $image->getClientOriginalName();
            $newName = $newFilenames[$index] . '.' . $image->getClientOriginalExtension();

            // Save to destination directory
            $destinationFullPath = $destinationPath . $newName;
            Storage::disk('network')->putFileAs($destinationPath, $image, $newName);

            // Rename file in source folder
            $sourceFullPath = $sourcePath . $originalName;
            $newSourcePath = $sourcePath . $newName;
            
            if (file_exists($sourceFullPath)) {
                rename($sourceFullPath, $newSourcePath);
            }
        }

        return response()->json(['message' => 'Images uploaded and renamed successfully']);
    }
}

I have tried above code for delete that time also same error message:

// Move the file to destination and remove from the source folder
if ($file->move($destinationPath, $newName)) {
    if (File::exists($source)) {
        File::delete($source);  // Removing the file from the source directory
    }
}

Error Message:

The process cannot access the file because it is being used by another process (code: 32)

We are using file upload Html form some time we will select file from any random folder also that time we will not take care of rename file into source folder.

Upvotes: 2

Views: 49

Answers (0)

Related Questions