Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : To rename an uploaded file automatically

Tags:

laravel

I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any file gets uploaded, in the database and in the folder after upload, the name of the file gets changed also when other user downloads the same file, renamed file will get downloaded. I tried:

if (Input::hasFile('file')){
        echo "Uploaded</br>";
        $file = Input::file('file');
        
        $file ->move('uploads');
        $fileName = Input::get('rename_to');
        
    }

But, the name gets changed to something like:

php5DEB.php

phpCFEC.php

What can I do to maintain the file in the same type and format and just change its name?

I also want to know how can I show the recently uploaded file on the page and make other users download it??

like image 643
Rock Avatar asked Jan 11 '17 10:01

Rock


People also ask

How can I change file name while uploading?

We can change file name by using FileUpload control's SaveAs method. SaveAs() method require to pass a parameter named filename. This parameter value is a string that specifies the full path of the location of the server on which to save the uploaded file.

How do you delete a file in Laravel?

You could use PHP's unlink() method just as @Khan suggested. But if you want to do it the Laravel way, use the File::delete() method instead. $files = array($file1, $file2); File::delete($files);


2 Answers

Use this one

$file->move($destinationPath, $fileName);
like image 131
ATIKON Avatar answered Oct 10 '22 21:10

ATIKON


For unique file Name saving

In 5.3 (best for me because use md5_file hashname in Illuminate\Http\UploadedFile):

public function saveFile(Request $request) {
    $file = $request->file('your_input_name')->store('your_path','your_disk');
}

In 5.4 (use not unique Str::random(40) hashname in Illuminate\Http\UploadedFile). I Use this code to ensure unique name:

public function saveFile(Request $request) {
    $md5Name = md5_file($request->file('your_input_name')->getRealPath());
    $guessExtension = $request->file('your_input_name')->guessExtension();
    $file = $request->file('your_input_name')->storeAs('your_path', $md5Name.'.'.$guessExtension  ,'your_disk');
}
like image 11
Sylvain Gagnot Avatar answered Oct 10 '22 20:10

Sylvain Gagnot