How to get the uploaded image name from the store method

微笑、不失礼 提交于 2020-02-06 11:37:21

问题


When I store an image in Laravel by doing:

$path = $request->file('myImage')->store('public/src/');

It returns the full path, but how do I get only the filename it was given?

This is an example of the returned path:

public/src/ltX4COwEmvxVqX4Lol81qfJZuPTrQO6S2jsicuyp.png


回答1:


Here, you can try this one.

    $fileNameWithExt = $request->file('myImage')->getClientOriginalName();
    $fileNameWithExt = str_replace(" ", "_", $fileNameWithExt);

    $filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
    $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);
    $filename = urlencode($filename);

    $extension = $request->file('myImage')->getClientOriginalExtension();

    $fileNameToStore = $filename.'_'.time().'.'.$extension;

    $path = $request->file('myImage')->storeAs('public/src/',$fileNameToStore);
    return $fileNameToStore;

You will get your stored filename in $fileNameToStore. Also, all the spaces will be replaced with "_" and you will get your stored filename with current time attached with it, which will help you differentiate between two files with the same name.




回答2:


In Laravel, the store() method generates the name dynamically .. so you can't get it from the store() method.

But you can use storeAs() method. Basically the store() method is calling the storeAs() method. So:

$path = $request->file('myImage')->store('public/src');

What Laravel is doing is calling ->storeAs('public/src', $request->file('myImage')->hashName()); .. you see the hashName() method? that is what generates the name.

So you can call hashName() first and know your name before the storing happens .. here is an example:

$uploadFile = $request->file('myImage');
$file_name = $uploadFile->hashName();
$path = $uploadFile->storeAs('public/src', $file_name);

Now you have $file_name and $path.

See:

  • https://laravel.com/docs/6.x/filesystem#file-uploads .. Specifying A File Name
  • https://github.com/laravel/framework/blob/6.x/src/Illuminate/Http/UploadedFile.php#L33
  • https://github.com/laravel/framework/blob/6.x/src/Illuminate/Http/FileHelpers.php#L42


来源:https://stackoverflow.com/questions/58856971/how-to-get-the-uploaded-image-name-from-the-store-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!