I am using Dropzone.js to upload multiple images in Laravel. Though Image is uploaded without any error, request is empty. Any solution for this?
HTML code
<form class="form-horizontal" id="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">ISSUE DATE / VOLUME NO</label>
<div class="col-sm-10"><input type="text" class="form-control" name="valume_no" value={{ old('valume_no') }}></div>
</div>
<div class="dropzone" id="my-dropzone">
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input name="featured_file" type="file[]" multiple />
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Done</button>
</div>
</div>
</form>
Dropzone configuration
Dropzone.autoDiscover = false;
$(document).ready(function () {
$("#my-dropzone").dropzone({
url: '{{ url("/news/uploadimgsaddmode") }}',
headers: {
'x-csrf-token': "{{ csrf_token() }}",
},
method: 'post',
paramName: "file",
maxFiles: 100,
maxFileSize: 100,
acceptedFiles: ".jpeg,.jpg,.png",
uploadMultiple: true,
parallelUploads: 100,
previewTemplate: document.querySelector('#preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
success: function (file, response) {
console.log(response);
}
});
});
Laravel Controller
public function uploadimgsaddmode(Request $request){
return Response::json(['message' => $request], 200);
}
Response
{"message":[{}]}
Related
Laravel Post html but as raw text
i'm use tinymce and normal input
i try to normal post and get with url and ajax
<div class="modal fade" id="addpromotion" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addpromotionLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="{{ route('admin.blog.create') }}" id="addpromotionform" method="post" enctype="multipart/form-data">
#csrf
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="modal-header">
<h1 class="modal-title fs-5" id="addpromotionLabel">เพิ่มโปรโมชั่น</h1>
{{-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> --}}
</div>
<div class="modal-body">
<div class="mb-3 mx-5">
<input type="file" class="form-control" name="image" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="title" class="form-control" placeholder="Title" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="description" class="form-control" placeholder="Description" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<textarea id="tinymcecreate" class="tinymce" name="body"></textarea>
</div>
<input type="hidden" name="type" value="promotion">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger">บันทึก</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ปิด</button>
</div>
</form>
</div>
</div>
</div>
body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E
when console.log ( data before post )
_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&csrf_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&title=qwqgqw&description=qgqg&body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E&type=promotion
$('#addpromotionform').on('submit', function(ed) {
tinymce.triggerSave();
ed.preventDefault();
var TinyAjaxPost = $('#addpromotionform').serialize();
var formData = new FormData(this);
console.log(TinyAjaxPost);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: formData,
cache:false,
dataType: 'html',
contentType: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});
but when post to controller i check with dd($request)
body don't have html tag but have only raw text ... custom
public function admin_blog_create(Request $request)
{
$file_name = time() . '.' . request()->image->getClientOriginalExtension();
$request->image->move(public_path('image/tinymce'), $file_name);
$tiny = [
'image' => $file_name,
'title' => $request->title,
'description' => $request->description,
'body' => $request->body,
'type' => 'blog',
];
blog::create($tiny);
return response()->json(['status'=>true, 'message' => $request->body]);
/* return redirect()->back(); */
}
and i try to use Get with url when check data with dd($request) have only raw text custom
Tools
Laravel 9
TinyMCE 6
How i post or get with full html to database ?
XSS Protection it is a problem.
i'm try to disable xss in controller
$this->middleware('XSS');
Can post ( request ) html data to database
enter image description here
Type this code if you are experiencing error 419
// Ajax CSRF Setup Code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The correct way to send, in addition to viewing the data in the console
$('#addpromotionform').on('submit', function(ed) {
ed.preventDefault();
//console log data
var TinyAjaxPost = $('#addpromotionform').serialize();
var copy = $("#addpromotionform iframe").contents().find('#tinymce').clone();
copy = $(copy).html();
console.log(TinyAjaxPost,copy);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});
I'm submitting my form using ajax in laravel
Output:
{"message":"The given data was invalid.","errors":{"name":["The name field is required."],"image":["The image field is required."]}}
View:
{{ Form::open(array('route' => 'ajax-add-record','enctype' => 'multipart/form-data','files'=> true,'class'=>'add','id'=>'frmadd')) }}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<h2 class="card-inside-title">Name</h2>
<div class="form-line focused">
{{ Form::text('name','',['class'=>'form-control','placeholder'=>'Name','id'=>'name']) }}
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6">
<div class="form-group">
<h2 class="card-inside-title">Image</h2>
<div class="form-line focused">
{{ Form::file('image',['class'=>'form-control']) }}
</div>
</div>
</div>
</div>
<button class="btn btn-info add_button btn-xs p-3 hide" type="button"><i class="material-icons">add</i> Add</button>
</div>
{{ Form::close()}}
Script:
$('#frmadd').submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: APP_URL+'/add',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response)
{
},
error: function(data)
{
}
});
});
Not a Duplicate Question!!!
Here is my code, using Laravel 5.4.
Form in .blade.php file:
<form id="read-data-form" name="form" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input name="comCode" id="comCode" type="hidden" value=""/>
<label><span class="text-danger">*</span> Upload File :</label>
<input name="file" id="fileToUpload" type="file" accept="text/*" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6 ">
<div class="text-right">
<button type="submit" class="btn operations-btn btn-default" id="upload">Upload</button>
<button type="button" class="btn operations-btn btn-default" id="stop">Stop</button>
</div>
</div>
</div>
</form>
Ajax-request in .js file:
$("form #read-data-form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var promise = $.ajax({
url: 'read_data/file/check',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
encode: true
});
promise.done(function(response){
});
promise.fail(function(error){
});
promise.always(function(){
});
}
Browser Console > Network > Headers > Request Payload:
Route in web.php file:
Route::post('read_data/file/check', 'ReadDataController#checkFile');
checkFile() method in ReadDataController.php file:
public function checkFile(Request $request)
{
$comCode = trim($request->comCode);
$file = $request->file('file');
dd($file);
}
Browser Console > Network > Preview > Request Payload:
This is how output of dd().
Issue:
File could not be captured as in a normal 'multipart/form-data' form without ajax request.
OK. Finally, I have a solution which is given by a senior person.
Removed this code:
$file = $request->file('file');
Added the following codes:
$uploadDirPath = 'C:/uploaded_files/';
$uploadFile = "moved_uploded_file.txt";
$request->file('file')->move($uploadDirPath, $uploadFile);
$uploaded_file = $uploadDirPath.$uploadFile;
I am trying to send form with upload file and multipart/form-data encoding using AJAX. I am using this form:
{!! Form::model($user, ['method' => 'PATCH', 'url' => ['/administrator/users', $user->id], 'class' => 'form-horizontal', 'files' => 'true', 'id' => 'userEdit']) !!}
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Avatar:</label>
<div class="col-sm-9">
<img src="/dashboard/assets/img/avatar/{{ $user->profile->avatar }}" class="img-circle m-b" />
<input type="file" name="avatar" />
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="first_name" value="{{ $user->profile->first_name }}" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Surname:</label>
<div class="col-sm-9">
<input type="text" name="last_name" value="{{ $user->profile->last_name }}" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" data-user-id="{{$user->id}}">Save</button>
</div>
{!! Form::close() !!}
I try to send data with Ajax like this:
$('#editUser').submit('#userEdit', function(event) {
event.preventDefault();
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: new FormData(userEdit),
processData: false,
contentType: false,
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
And in result, I cannot read inputs from request in controller. It returns an empty array.
public function update($id, Request $request){
dd($request->all());
}
I think that I'm doing something wrong with sending multipart data. How to send it correctly?
It seems that you aren't adding FormData properly and your event seems to be broken, you should add the data in ajax like this:
$('#editUser').on('submit', function(event) {
event.preventDefault();
var form = $(this); // You need to use standard JS object here
var formData = new FormData(form);
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
Hope this helps!
I can not get the formData from the file upload
form.blade.php
<form method="POST" class="form-horizontal" enctype="multipart/form-data" id="modal-file-upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="folder" value="" id="modal-file-upload-folder">
<div class="modal-header">
<h4 class="modal-title">Upload New File</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="file" class="col-sm-3 control-label">
File
</label>
<div class="col-sm-8">
<input multiple="true" accept="image/*" required="true" id="fileToUpload" type="file" name="file[]">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="close_upload_view()">Cancel</button>
<button class="btn btn-primary" id="btn-upload">Upload File</button>
</div>
</form>
Controller
public function uploadMultiFile(Request $request) {
// getting all of the post data
$data = $request->input('formData');
var_dump($data); current return null
}
<script>
// Confirm file delete
function close_upload_view() {
$("#modal-file-upload").modal("hide");
return false;
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$("#modal-file-upload").submit(function(e){
e.preventDefault();
//var formData = new FormData(document.getElementById('modal-file-upload')[0]);
var fd = new FormData();
var ins=document.getElementById('fileToUpload').files.length;
for(var x=0;x<ins;x++)
{
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}
var folder = $("input#modal-file-upload-folder").val();
var token = $("input[name=_token]").val();
var dataString = 'formData='+fd+'&folder='+folder+'&token='+token;
$.ajax({
type: "POST",
url: '{!! url() !!}/admin/upload/multifile',
cache: false,
data : dataString,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server it
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
</script>