Como Adicionar Link De Download No Dropzone Com Laravel 8

Com o uso do Dropzone, você pode adicionar facilmente a área de upload de arquivos de arrastar e soltar. Ele exibe uma miniatura após o upload do arquivo, mas não exibe um link para download.

Neste tutorial, mostro como você pode adicionar o link do arquivo de download no contêiner Dropzone depois que o arquivo for carregado com sucesso no Laravel 8.

1. Baixar

  • Baixe a biblioteca Dropzone aqui
  • Extraia o arquivo baixado no public/ diretório.

2. Controlador

  • Criar  PageController controlador.
php artisan make:controller PageController
  • Abrir  app/Http/Controllers/PageController.php arquivo.
  • Crie dois métodos –
    • index – Carregar  index visualização.
    • uploadFile –  Este método é usado para fazer upload do arquivo selecionado do Dropzone.

Defina a validação do arquivo. Eu defino o tamanho máximo do arquivo para 2 MB (2048 Kb).

Se o arquivo não for validado, atribua  0 a  $data['success'] e a resposta de validação a  $data['error'].

Se o arquivo for validado com sucesso, carregue o arquivo para o "files"local. Armazene o caminho do arquivo carregado na $filepathvariável.

Atribuir 1a $data['success'], $filepatha $data['link']e atribuir Uploaded Successfully!a $data['message'].

Matriz de retorno $datano formato JSON.

Código concluído

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PageController extends Controller {

     public function index(){
          return view('index');
     }

     public function uploadFile(Request $request){

          $data = array();

          $validator = Validator::make($request->all(), [
               'file' => 'required|mimes:png,jpg,jpeg,pdf|max:2048'
          ]);

          if ($validator->fails()) {
 
              $data['success'] = 0;
              $data['error'] = $validator->errors()->first('file');// Error response

          }else{
               if($request->file('file')) {

                   $file = $request->file('file');
                   $filename = time().'_'.$file->getClientOriginalName();

                    // File upload location
                    $location = 'files';

                    // Upload file
                    $file->move($location,$filename);

                    // File path
                    $filepath = url($location.'/'.$filename);

                    // Response
                    $data['success'] = 1;
                    $data['link'] = $filepath;
                    $data['message'] = 'Uploaded Successfully!';

               }else{
                     // Response
                     $data['success'] = 0;
                     $data['message'] = 'File not uploaded.'; 
               }
          }

           return response()->json($data);
     }
}

3. Rota

  • Abrir routes/web.phparquivo.
  • Defina 2 rotas –
use App\Http\Controllers\PageController;

Route::get('/', [PageController::class, 'index']);
Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');
  • A segunda rota é usada para upload de arquivos Dropzone.

4. Visualizar

Criar  index.blade.php arquivo na  resources/views/ pasta.

Armazene o token CSRF na <meta >tag e inclua a biblioteca Dropzone.

Contêiner Dropzone 

  • Crie um <form action="{{route('uploadFile')}}" class='dropzone' >.

Roteiro

  • Leia o token CSRF da <meta >tag e atribua à CSRF_TOKENvariável.
  • Desative o autoDiscover do dropzone – Dropzone.autoDiscover = falsee inicialize o Dropzone no formato <form >.
  • Defina o tamanho máximo do arquivo de upload para 2 MB e extensões de arquivo válidas – “.jpeg,.jpg,.png,.pdf”.
  • Envie o token CSRF usando o sendingevento – formData.append("_token", CSRF_TOKEN);.
  • Usando successa resposta de retorno de verificação de evento e adicione o link de download.
  • Se response.status == 0então exibir a mensagem de erro usando alert()o contrário, exiba o link de download criando uma marca de âncora e defina hrefcomo response.link.

Código concluído

<!DOCTYPE html>
<html>
<head>
      <title>How to Add Download link in Dropzone - Laravel 8</title>

      <!-- Meta -->
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <meta charset="utf-8">
      <meta name="csrf-token" content="{{ csrf_token() }}">

      <!-- CSS -->
     <link rel="stylesheet" type="text/css" href="{{asset('dropzone/dist/min/dropzone.min.css')}}">

      <!-- JS -->
      <script src="{{asset('dropzone/dist/min/dropzone.min.js')}}" type="text/javascript"></script>

</head>
<body>

       <div class='content'>
              <!-- Dropzone -->
             <form action="{{route('uploadFile')}}" class='dropzone' ></form> 
       </div>

       <!-- Script -->
       <script>
       var CSRF_TOKEN = document.querySelector('meta[name="csrf-token"]').getAttribute("content");

       Dropzone.autoDiscover = false;
       var myDropzone = new Dropzone(".dropzone",{ 
            maxFilesize: 2, // 2 mb
            acceptedFiles: ".jpeg,.jpg,.png,.pdf",
       });
       myDropzone.on("sending", function(file, xhr, formData) {
            formData.append("_token", CSRF_TOKEN);
       }); 
       myDropzone.on("success", function(file, response) {

            if(response.success == 0){ // Error
                  alert(response.error);
            }else{
                  // Download link
                  var anchorEl = document.createElement('a');
                  anchorEl.setAttribute('href',response.link);
                  anchorEl.setAttribute('target','_blank');
                  anchorEl.innerHTML = "<br>Download";
                  file.previewTemplate.appendChild(anchorEl);
             }

       });
       </script>

</body>
</html>

5. Saída

Ver saída


6. Conclusão

Eu adicionei um link de download usando o elemento âncora quando o arquivo foi carregado com sucesso. Caminho do arquivo retornado com status de upload do controlador.

Fonte:  https://makitweb.com

#php #laravel 

What is GEEK

Buddha Community

Como Adicionar Link De Download No Dropzone Com Laravel 8

I am Developer

1617089618

Laravel 8 Tutorial for Beginners

Hello everyone! I just updated this tutorial for Laravel 8. In this tutorial, we’ll go through the basics of the Laravel framework by building a simple blogging system. Note that this tutorial is only for beginners who are interested in web development but don’t know where to start. Check it out if you are interested: Laravel Tutorial For Beginners

Laravel is a very powerful framework that follows the MVC structure. It is designed for web developers who need a simple, elegant yet powerful toolkit to build a fully-featured website.

Recommended:-Laravel Try Catch

#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners

I am Developer

1599536794

Laravel 8 New Features | Release Notes - Tuts Make

In this post, i will show you what’s new in laravel 8 version.

#What’s new in Laravel 8?

  • 1 - Change Path Of Default Models Directory
  • 2 - Removed Controllers Namespace Prefix
  • 3 - Enhancements on php artisan serve
  • 4 - Enhanced Rate Limiting
  • 5 - Enhanced on Route Caching
  • 6 - Update on Pagination Design
  • 8 - Dynamic Blade Componenets
  • 7 - Update Syntax for Closure Based Event Listeners
  • 8 - Queueable Model Event Listeners
  • 9 - Maintenance mode: secret access
  • 10 - Maintenance mode: pre-rendered page
  • 11 - Queued job batching
  • 12 - Queue backoff()
  • 13 - Laravel Factory

https://www.tutsmake.com/laravel-8-new-features-release-notes/

#laravel 8 features #laravel 8 release date #laravel 8 tutorial #news - laravel 8 new features #what's new in laravel 8 #laravel 8 release notes

I am Developer

1602038680

Drag and Drop file upload using Dropzone in Laravel 8

Laravel 8 drag and drop multiple file upload dropzone js laravel 8 dropzone example. In this tutorial, you will learn, laravel 8 dropzone multiple files. OR understand the concept of laravel 8 dropzone image file upload.

And learn how to upload multiple image file without refresh or reload the whole web page using dropzone js in laravel 8 app.

Note that, Dropzone.js is a jquery plugin, dropzone.js through you can select one by one image and also with preview. After choose image from browse you can see preview of image. dropzone.js also provide filter like we can make validation for max upload, specific image or file extension etc.

In this example tutorial, we will create two routes, one for display dropzone image upload form view and another for store image file. Then, create two methods on DropzoneController.

Drag & Drop File Uploading using Laravel 8 Dropzone JS

Step 1 – Download Laravel 8 Application
Step 2 – Setup Database with App
Step 3 – Create Model & Migration
Step 4 – Create Routes
Step 5 – Generate Controller By Artisan Command
Step 6 – Create Blade View
Step 7 – Implement javascript Code for Dropzone Configuration
Step 8 – Create Images Directory inside Public Directory
Step 9 – Run Development Server

https://www.tutsmake.com/laravel-8-drag-and-drop-file-upload-using-dropzone-tutorial/

#dropzone multiple file upload laravel 8 #dropzone multiple image upload laravel 8 #multiple image upload with dropzone.js in laravel 8 #laravel 8 dropzone js multiple file upload

Yogi Gurjar

1600308055

Laravel 8 Form Validation Tutorial

Laravel 8 form validation example. In this tutorial, i will show you how to submit form with validation in laravel 8.

And you will learn how to store form data in laravel 8. Also validate form data before store to db.

How to Validate Form Data in Laravel 8

  1. Step 1 – Install Laravel 8 Application
  2. Step 2 – Configuring Database using Env File
  3. Step 3 – Create Model & Migration File For Form
  4. Step 4 – Create Routes
  5. Step 5 – Creating Controller
  6. Step 6 – Create Blade File For Form
  7. Step 7 – Start Development Server
  8. Step 8 – Run Laravel 8 Form Validation App On Browser

https://laratutorials.com/laravel-8-form-validation-example-tutorial/

#laravel 8 form validation #laravel 8 form validation tutorial #laravel 8 form validation - google search #how to validate form data in laravel 8 #form validation in laravel 8

I am Developer

1609729452

Laravel 8 Tutorial For Beginners Step by Step

Recommended:- Laravel Try Catch

#laravel #laravel 8 tutoral #laravel 8 tutorial for beginners #laravel 8 tutorial for beginners step by step #laravel 8 tutorial from scratch