1658198640
С помощью Dropzone вы можете легко добавить область загрузки файлов методом перетаскивания. Он отображает миниатюру после загрузки файла, но не отображает ссылку для загрузки.
В этом руководстве я покажу, как вы можете добавить ссылку на скачивание файла в контейнер Dropzone после того, как файл будет успешно загружен в Laravel 8.
public/
каталог.PageController
контроллер.php artisan make:controller PageController
app/Http/Controllers/PageController.php
файл.index
представление.Определите проверку файлов. Я установил максимальный размер файла 2 МБ (2048 КБ).
Если файл не проверен, назначьте 0
и $data['success']
ответ проверки на $data['error']
.
Если файл успешно проверен, загрузите файл в папку "files"
. Сохраните путь к загруженному файлу в $filepath
переменной.
Назначить , на и назначить . 1
_$data['success']$filepath$data['link']Uploaded Successfully!$data['message']
Возвращает $data
массив в формате JSON.
Завершенный код
<?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);
}
}
routes/web.php
файл.use App\Http\Controllers\PageController;
Route::get('/', [PageController::class, 'index']);
Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');
Создать index.blade.php
файл в resources/views/
папке.
Сохраните токен CSRF в <meta >
теге и включите библиотеку Dropzone.
Контейнер Дропзоны
<form action="{{route('uploadFile')}}" class='dropzone' >
.Скрипт
<meta >
тега и назначьте его CSRF_TOKEN
переменной.Dropzone.autoDiscover = false
и инициализируйте Dropzone в <form >
.sending
события – formData.append("_token", CSRF_TOKEN);
.success
проверку события, верните ответ и добавьте ссылку для скачивания.response.status == 0
затем отобразить сообщение об ошибке, используя alert()
иное, отобразить ссылку для загрузки, создав тег привязки и установив href
значение response.link
.Завершенный код
<!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>
Я добавил ссылку для загрузки, используя элемент привязки, когда файл был успешно загружен. Возвращаемый путь к файлу со статусом загрузки из контроллера.
Источник: https://makitweb.com
1617089618
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.
#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners
1599536794
In this post, i will show you what’s new in laravel 8 version.
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
1602038680
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.
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
1600308055
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.
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
1609729452
#laravel #laravel 8 tutoral #laravel 8 tutorial for beginners #laravel 8 tutorial for beginners step by step #laravel 8 tutorial from scratch