Laravel : To rename an uploaded file automatically

后端 未结 7 1312
北海茫月
北海茫月 2020-12-11 04:31

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 fil

相关标签:
7条回答
  • 2020-12-11 04:46

    at the top after namespace use Storage;

        Just do something like this ....
    

    // read files $excel = $request->file('file');

    // rename file
    $excelName = time().$excel->getClientOriginalName();
    
    // rename to anything
    $excelName = substr($excelName, strpos($excelName, '.c'));
    $excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;
    $excel->move(public_path('equities'),$excelName);
    

    This guy collect the extension only:

     $excelName = substr($excelName, strpos($excelName, '.c'));
    

    This guy rename its: $excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;

    0 讨论(0)
  • 2020-12-11 04:52

    You can use php core function rename(oldname,newName) http://php.net/manual/en/function.rename.php

    0 讨论(0)
  • 2020-12-11 04:53

    Use this one

    $file->move($destinationPath, $fileName);
    
    0 讨论(0)
  • 2020-12-11 05:02

    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');
    }
    
    0 讨论(0)
  • 2020-12-11 05:04

    You can rename your uploaded file as you want . you can use either move or storeAs method with appropiate param.

    $destinationPath = 'uploads';
    $file = $request->file('product_image');
    foreach($file as $singleFile){
        $original_name = strtolower(trim($singleFile->getClientOriginalName()));
        $file_name = time().rand(100,999).$original_name;
         // use one of following 
        // $singleFile->move($destinationPath,$file_name); public folder
        // $singleFile->storeAs('product',$file_name);  storage folder
        $fileArray[] = $file_name;
    }
    print_r($fileArray);
    
    0 讨论(0)
  • 2020-12-11 05:04

    correct usage.

    $fileName = Input::get('rename_to');
    Input::file('photo')->move($destinationPath, $fileName);
    
    0 讨论(0)
提交回复
热议问题