R
R
Roman2019-03-17 20:03:38
Laravel
Roman, 2019-03-17 20:03:38

How in Laravel to upload files through a form and store them in the database (the files themselves, not names or links)?

Hello.
The customer wants files from the user form to be saved in the database (BLOB type field)
How can this be implemented in Laravel?
Is this even possible in Laravel?
And yes, is it possible to send and save the file at the same time as other data from the form? In one form.
Otherwise, the documentation considers the case of a separate file download with a separate controller.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-03-17
@procode

Well, it seems that after trial and error + Google it works :)
Two points:
without enctype, the file is not loaded, don't forget, don't be like me))
In the controller, something like this now:

$file = $request->inputname; // inputname - это name поля из формы			
$filecontent = $file->openFile()->fread($file->getSize()); // эта магия из стэковерфлоу 
//что за openFile() - я не понимаю... 
$filename = $file->getClientOriginalName();  // getClientOriginalName() - тоже какой-то секретный
//метод))) в документации его нет)) но это работает!))

here is such a mysterious code)))))))))
can be useful to someone

A
Alex Wells, 2019-03-17
@Alex_Wells

Question: why the hell is this to the customer? Since when does the customer decide what architectural solutions the programmer uses?
If it was a team leader or another programmer, then yes, you can, but you need to take into account the nuances. For example, in my project I store small archives (700 bytes) in radish, since there are a lot of files (which is not good for the file system), and this is not storage, but just a cache, which cleans itself. In this case, yes, you can use a database to store files, but this is one of the exceptions, not the norm .
In my case, the zip archive was converted to string by the library, and distributed like this:

/**
     * Return file from string (buffer).
     *
     * @param $content
     * @param null   $name
     * @param array  $headers
     * @param string $disposition
     *
     * @return \Symfony\Component\HttpFoundation\StreamedResponse
     */
    public function fileFromString($content, $name, array $headers = [], $disposition = 'attachment')
    {
        return response()->streamDownload(function () use ($content) {
            echo $content;
        }, $name, [
            'Content-Type' => MimeType::from($name),
        ] + $headers, $disposition);
    }

With blob it should be +- the same way. But I repeat that this is an edge case, and usually you should not do this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question