Laravel:自动重命名上传的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41588306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:36:41  来源:igfitidea点击:

Laravel : To rename an uploaded file automatically

laravel

提问by Rock

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

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??

我也想知道如何在页面上显示最近上传的文件并让其他用户下载它??

回答by ATIKON

Use this one

用这个

$file->move($destinationPath, $fileName);

回答by Sylvain Gagnot

For unique file Name saving

用于唯一文件名保存

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

在 5.3 中(最适合我,因为在 Illuminate\Http\UploadedFile 中使用 md5_file 哈希名称):

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:

在 5.4 中(在 Illuminate\Http\UploadedFile 中使用非唯一的 Str::random(40) 哈希名)。我使用此代码来确保名称唯一:

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');
}

回答by ujwal dhakal

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

可以使用php核心功能rename(oldname,newName)http://php.net/manual/en/function.rename.php

回答by Gayan

Find this tutorial helpful. file uploads 101

发现本教程很有帮助。 文件上传 101

Everything you need to know about file upload is there.

您需要了解的有关文件上传的所有信息都在此处。

-- Edit --

- 编辑 -

I modified my answer as below after valuable input from @cpburnz and @Moinuddin Quadri. Thanks guys.

在@cpburnz 和@Moinuddin Quadri 提供宝贵意见后,我修改了我的答案如下。谢谢你们。

First your storage driver should look like this in /your-app/config/filesystems.php

首先,您的存储驱动程序应如下所示 /your-app/config/filesystems.php

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'), // hence /your-app/storage/app/public
    'visibility' => 'public',
],

You can use other file drivers like s3but for my example I'm working on localdriver.

您可以使用其他文件驱动程序,s3但在我的示例中,我正在研究localdriver.

In your Controlleryou do the following.

在你的Controller你做以下。

$file = request()->file('file'); // Get the file from request
$yourModel->create([
    'file' => $file->store('my_files', 'public'),
]);

Your file get uploaded to /your-app/storage/app/public/my_files/and you can access the uploaded file like

您的文件被上传到/your-app/storage/app/public/my_files/,您可以访问上传的文件,例如

asset('storage/'.$yourModel->image)

Make sure you do

确保你这样做

php artisan storage:link

to generate a simlinkin your /your-app/public/that points to /your-app/storage/app/publicso you could access your files publicly. More info on filesystem - the public disk.

在您的指向中生成一个simlink,以便您可以公开访问您的文件。有关文件系统的更多信息 - 公共磁盘。/your-app/public//your-app/storage/app/public

By this approach you could persists the same file name as that is uploaded. And the great thing is Laravelgenerates an unique name for the file so there could be no duplicates.

通过这种方法,您可以保留与上传的文件名相同的文件名。伟大的事情是Laravel为文件生成一个唯一的名称,因此不会有重复。

To answer the second part of your question that is to show recently uploaded files, as you persist a reference for the file in the database, you could access them by your database record and make it ->orderBy('id', 'DESC');. You could use whatever your logic is and order by descending order.

要回答问题的第二部分,即显示最近上传的文件,当您在数据库中保留文件的引用时,您可以通过数据库记录访问它们并使其成为->orderBy('id', 'DESC');。您可以使用任何逻辑并按降序排列。

回答by infomasud

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

您可以根据需要重命名上传的文件。您可以使用带有适当参数的 move 或 storeAs 方法。

$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);

回答by Delino

at the top after namespace use Storage;

在命名空间使用存储之后的顶部;

    Just do something like this ....

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

// 读取文件 $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;

这家伙重命名它: $excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;

回答by Arun Code

correct usage.

正确使用。

$fileName = Input::get('rename_to');
Input::file('photo')->move($destinationPath, $fileName);