How to download a file to the server with php Laravel

Asked

Viewed 2,516 times

1

I would like to know how to download an image or video using Laravel and save on my server direct, taking a url as example: https://brandmark.io/logo-rank/random/beats.png?

1 answer

2


First we create the fields in the View:

<!DOCTYPE html>
<html>
<body>

<form action="/arquivos" method="post" enctype="multipart/form-data">
    <input type="file" name="arquivo">
    <input type="submit" value="Enviar" name="submit">
</form>

</body>
</html>

Then we create the route to the Controller:

Route::post('/arquivo', 'ArquivoController@store');

Here you can use the standard PHP methods like:

To check if a file has been uploaded

if ( isset( $_FILES[ 'arquivo' ][ 'name' ] ) && $_FILES[ 'arquivo' ][ 'error' ] == 0 )

Take the extension and restrict to images only:

$extensao = pathinfo ( $nome, PATHINFO_EXTENSION );
$extensao = strtolower ( $extensao );

if ( strstr ( '.jpg;.jpeg;.gif;.png', $extensao ) ) {

    $novoNome = uniqid ( time () ) . '.' . $extensao;
    $destino = 'imagens / ' . $novoNome;

    if ( @move_uploaded_file ( $arquivo_tmp, $destino ) ) {
        return 'sucesso ao enviar! ';
    } else {
       return 'erro ao enviar!';
    }
}

Here in case the files will be saved in the directory: /public or /public/images since in the codes we create this directory.

In the Laravel documentation there is a specific class to handle this Storage. To use it you will need to create a symbolic link between the folders of your project Standard: public/Storage, Storage/app/public, you must do this as a security measure: just go to the console in your project folder and use the command:

php artisan storage:link

Then you need to reference the Storage class in your controller:

<?php

namespace App\Http\Controllers;

use Storage; // <--------
use Illuminate\Http\Request;

class ArquivoController extends Controller
{

Then you use the request(); method to get the file information:

$arquivo = new Arquivo(); // cria uma instancia do arquivo 

$arquivo->nomeArquivo = request()->file('arquivo')->getClientOriginalName();
$arquivo->destino = "imagens/";
$arquivo->extensao = strtolower(request()->file('arquivo')->getClientOriginalExtension());
$arquivo->tamanho = request()->file('arquivo')->getSize();

if ( strstr ( '.jpg;.jpeg;.gif;.png', $arquivo->extensao ) ) {
    // Verifica se exite o diretorio, se não cria o diretorio;
    if (!Storage::exists("public/".$arquivo->destino)) {
        Storage::makeDirectory("public/".$arquivo->destino, 0777, true);
    }

    Storage::put("public/".$arquivo->destino, file_get_contents(request()->file('arquivo')));

    $arquivo->save(); // salva um registro no banco de dados sobre esse arquivo

    return "Imagem enviada com sucesso!";
} else {
    return "Erro! Tipo de Arquivo não é uma imagem!";
}

To get the file url you use this code here:

$arquivo = Arquivo::findOrFail($id);

$url = Storage::url($arquivo->destino."/".$arquivo->nome);

return $url;

If you want to make available to the user to download the image you can redirect it to another page for him to download, here I did not use the Storage, but it also has a method to download:

$arquivo = Arquivo::findOrFail($id);

return response()->download(storage_path("app/public/".$arquivo->destino."/".$arquivo->nome));

Here are some websites I used to upload files:

W3schools, has a very basic tutorial on how to do using native PHP methods, but is in English.

Eduardokraus, English tutorial using native PHP methods.

Documentation Laravel v5.5, The documentation of the file system they created, here is more details about the Storage. The documentation is in English, but I recommend that you read it with the help of a translator as it explains the full functionality of the class. I used 5.5..

If you want to use a Drag&drop system to upload files recommend these tutorials (need Javascript/Jquery):

talkerscode, the only problem with this site is that it is very polluted.

css-Tricks, this one has a more presentable tutorial, plus it’s a little more complicated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.