Laravel 5.3 Storage::put creates a directory with the file name

萝らか妹 提交于 2019-12-06 17:12:30

问题


I'm using Laravel's file storage functionality to save a file:

public function dataPost(Request $request) {

    $fileInForm = 'doc';

    if ($request->hasFile($fileInForm)) {

        $file = $request->file($fileInForm);
        if ($file->isValid()) {

            // Filename is hashed filename + part of timestamp
            $hashedName = hash_file('md5', $file->path());
            $timestamp = microtime() * 1000000;

            $newFilename = $hashedName . $timestamp . '.' . $file->getClientOriginalExtension();

            Storage::disk('local')->put($newFilename, $file);
        }
    }
}

This does save the file, but inside a directory named the same as the file, for example:

storage/app/952d6c009.jpg/952d6c009.jpg

or

storage/app/234234234.jpg/234234234.jpg

Is this expected? Is there any way to just store the file without a separate directory for each file?

Thanks!


回答1:


you need to provide the file contents in the second argument not file object, try this:

Storage::disk('local')->put($newFilename, file_get_contents($file));




回答2:


This happened because you specify the directory to store as filename. The newFilename, should be the directory name such as 'images'. Refer to this line

Storage::disk('local')->put($newFilename, $file);

So you could change this to

Storage::disk('local')->putFile('images', $file);

Then you will get the path stored at storage/app/images/234234234.jpg




回答3:


Storage::disk('local')->putFileAs('', $file, $filenewname);



回答4:


$file is encoded.You have to unencode the file.

Storage::disk('local')->put($newFilename, File::get($file));



来源:https://stackoverflow.com/questions/40002275/laravel-5-3-storageput-creates-a-directory-with-the-file-name

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