Reputation: 213
I am working with Laravel 5.4 and want to upload a file (let's call it "lorem.ext") to the storage directory (storage/app/) "path/to/file" with a unique file name.
For that I want to use Storage::putFile (https://laravel.com/docs/5.4/filesystem#storing-files) which not only stores my file, but also automatically creates a unique file name.
The documentation says to use such:
Storage::putFile('uploadedFile', new File('/path/to/file'));
Using this, I will get the error
FileNotFoundException in File.php line 37: The file "/path/to/file" does not exist
My further thoughts:
I honestly do not know exactly what the signature means and never found a working example from putFile in the web. In the documentation it is not described and looking closer (https://laravel.com/api/5.4/Illuminate/Filesystem/FilesystemAdapter.html#method_putFile) there is no information, as well.
What I think it means:
The first parameter "uploadedFile" (or as https://laravel.com/docs/5.4/filesystem#storing-files calls it: "photos") will automatically get the file via the ID from the form in the view:
<input type="file" id="uploadedFile" name="uploadedFile">
and there is no need anymore to load it via
request()->file('uploadedFile')
The second parameter "new File('/path/to/file')" (or as https://laravel.com/docs/5.4/filesystem#storing-files calls it: "new File('/path/to/photo')") will specify the path in the target storage directory on the server without the file name:
.../storage/app/path/to/file/formerLoremNowUniqueFileName.ext
So complete example where I can upload my lorem.ext and it will get stored on .../storage/app/path/to/file/formerLoremNowUniqueFileName.ext (which does not work):
View:
<form method="POST" action="URL/TO/STORE" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" id="uploadedFile" name="uploadedFile">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
Controller:
public function store() {
return Storage::putFile('uploadedFile', new File('/path/to/file'));
}
Can anybody
Thank you!
Upvotes: 3
Views: 17360
Reputation: 2744
First argument passed to putFile
is the new file location. Example: /path/to/new/file/
The second argument is a File
or UploadedFile
instance. This can come from request()->file('uploadedFile')
.
Thus your controller should read
public function store() {
return Storage::putFile(
storage_path('uploads'),
request()->file('uploadedFile')
);
}
A generated hash will be used for the file name.
Upvotes: 4