Dropzone Multiple File upload not working For Excel File - javascript

I have facing a problem in Dropzone and Laravel 5.7. I am currently upload excel file to via dropzone. But it is not working correctly. For example If I add 10 files then In my database there is 10 entry with different file name but On file Storage folder there are not 10 files, It varies from 6,7,8 File. I am changing my php.ini file for upload_max_filesize and max_file_uploads. Here is my code snippet.
My Js Code
<script type="text/javascript">
Dropzone.options.dropzone =
{
parallelUploads: 1, // Uploads one (1) file at a time, change to whatever you like.
autoProcessQueue: true,
uploadMultiple: true,
maxFiles: 100,
maxFilesize: 3,
autoQueue: true,
renameFile: function (file) {
var dt = new Date();
var time = dt.getTime();
return time + file.name;
},
addRemoveLinks: true,
timeout: 50000,
removedfile: function (file)
{
var name = file.upload.filename;
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
type: 'POST',
url: '{{ url("admin.pos.deleteexcel") }}',
data: {filename: name},
success: function (data) {
console.log("File has been successfully removed!!");
},
error: function (e) {
console.log(e);
}});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
success: function (file, response)
{
console.log(response);
},
error: function (file, response)
{
return false;
}
};
</script>
My Form is
{!! Form::open(['method'=>'POST', 'action'=>'backend\ExcelController#multipleExcelStore', 'files'=>true, 'id' => 'dropzone_form', 'class'=>'dropzone needsclick dz-clickable']) !!}
<div class="dz-message needsclick">
<div class="search-block">
<div class="row">
<div class="col-xs-12">
<div class="upload_container">
<div class="upbtn_block_1">
Drag & drop Files Here
</div><!--/upbtn_block_1 -->
<div class="up_text_block">Or</div>
<div class="upload_btn"><span>Browse File</span></div>
</div>
</div>
</div>
</div>
</div>
{!! Form::close() !!}
And My controller code
public function multipleExcelStore(Request $request) {
$input = [];
$imageName = Carbon::now()->format('Y') . '/' . Carbon::now()->format('m') . '/' . uniqid() . '_' . time() . '.' . $request->file('file')->getClientOriginalExtension();
$destinationPath = Config::get('constants.PO_MULTILE_ATTACHEMNT') . '/';
Helper::uploadFile($request->file('file'), null, $destinationPath, $imageName);
$input['attachment'] = Config::get('constants.PO_MULTILE_ATTACHEMNT') . '/' . $imageName;
$input['process_user_id'] = Auth::guard('admin')->user()->id;
$input['process_ip'] = $request->ip();
$input['name'] = $request->file('file')->getClientOriginalName();
PosExcel::create($input);
return response()->json(['success' => $imageName]);
}
I google it but return without any success.
Thank You

Have you tryed to remove
autoProcessQueue: true,
uploadMultiple: true,
I have another project with multiple upload and dont need to use that argument in the javascript, Queue is possible that is the problem too, try it and tell us :)
good luck

Related

Dropzone is uploading all files to server for each file drop/selection

I'm trying to integrate dropzone in a laravel 8 application. Whenever I drop any image in dropzone, it is uploading all the files of dropzone, not skipping already uploaded file. For example, if I drop "image-1.jpg" in dropzone, it uploads the file instantly (which is desired). But after that, if I select "image-2.jpg", it re-uploads "image-1.jpg" first (which isn't desired, I want to prevent this re-upload), then it uploads "image-2.jpg". Also, I want to prevent folder(containing multiple image) upload and have tried to prevent it by setting maxFiles to 1, but it's not preventing it.
Javascript
var refType = $('#reference-type');
electronic = $('.electronic'),
image = $('.image'),
description = $('.description'),
url = "{{ route('user.bank.files') }}",
submitRef = $('#submit-ref');
Dropzone.autoDiscover=false;
var imageDropzone;
var config = {
url: url, headers: {'X-CSRF-TOKEN':'{{ csrf_token() }}'},
uploadMultiple: false,
maxFiles: 1,
maxFilesize: 1,
paramName: 'reference_image',
addRemoveLinks: true,
acceptedFiles: 'image/jpeg, image/png , image/jpg, image/svg',
init: function() {
imageDropzone = this;
},
removedfile: function (file) {
if (file.accepted) {
data = {
action: 'delete',
tnx_id: "{{ the_tnx(data_get($order, 'tnx')) }}"
};
NioApp.Form.toPost(url, data);
}
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
sending: function(data, xhr, formData) {
formData.append('action', 'store');
formData.append('tnx_id', "{{ the_tnx(data_get($order, 'tnx')) }}");
},
addedfiles: function () {
if (this.files.length > 1) {
this.removeFile(this.files[1]);
NioApp.Toast("{{ __('You can upload only one :file.', ['file' => 'image']) }}", 'warning');
}
},
error: function(file, errorMessage) {
$.each(imageDropzone.files, function(i, file) {
file.status = Dropzone.QUEUED
});
}
};
$("#reference-image").dropzone({...config});

why is my variable empty in my controller?

I am trying to make an upload function to upload multiple files. But everytime if i check in my controller where I send the data to the variable is empty. What am I doing wrong please help.
This is the form where i get the myfiles variable
<form name="Document" method="post" action enctype="multipart/form-data">
<div class="col-md-6">
<input type="file" id="documento" name="myFiles[]" required="required" multiple>
</div>
</form>
This is my script that i wrote that makes it an array and get the files based on the id documentto.
$(document).on('click', '#btnSaveUploadedFiles', function(e){
e.preventDefault();
var fileArray = [];
var fileBag = new FormData();
var files = document.getElementById('documento').files;
var arrayOfAllUploadedFiles = Array.from(files);
fileArray.forEach(file => fileBag.append("myFiles[]", file));
console.log(files);
$.ajax({
url: "{{ admin.generateUrl("uploadFiles") }}",
traditional: true,
data: {
"files": fileBag,
"uniqId": "{{ admin.uniqId }}",
"reservation": {{ admin.subject.id }}
},
processData: false,
contentType: false,
type: 'POST',
success: function () {
Swal.fire({
title: "test",
icon: "success",
confirmButtonText: "Sluiten"
});
},
});
});
This is my controller of symfony where i get the data from the {{ admin.generateurl.uploadfiles }}
public function uploadFilesAction(Request $request)
{
$reservationID = $request->get('reservation');
$files = $request->files;
dd($files);
$directory = "images/uploads/";
foreach ($files as $uploadedFile) {
// name the resulting file
$name = $reservationID;
$file = $uploadedFile->move($directory, $name);
// do something with the actual file
$this->doSomething($file);
}
// return data to the frontend
return new JsonResponse();
}
if you need more information ask me

Dropzone.js - How to add new property to file object after uploading file

I'm using dropzone and PHP to upload and delete files. When I load my upload page I create some mockfiles with the following params: name, size, thumbnail and id. This mock is set using pre uploaded data.
So when someone click on remove file button, I call the php method that delete the image.
My problem is when the user uploads an file and tries to delete it without loading the page. When it happens, dropzone file object just can't be altered.
I'm trying:
var dropZone3 = new Dropzone("#file3",{
init: function() {
this.on('success', function (file) {
console.log(file);
file['test'] = 'test';
file.test = 'test';
console.log(file);
})
},
paramName: 'file3',
autoProcessQueue:true,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: 3,
maxFilesize: 5,
addRemoveLinks: true
My problem is that the first console.log and the second one inside init on success function shows me the same file.
Anyone knows how to fix it?
Thank you in advance.
It's possible to add properties directly to file object (dropzone v4.3.0)
var dropZone = new Dropzone(document.querySelector('.js-dropzone'), {
url: '/file/upload'
});
dropZone.on('success', function (file, response) {
var res = JSON.parse(response);
if (res.result == true) {
file.test = 'test';
file.id = res.id;
}
});
Don't think you can add a property to the file object when is already uploaded, but you can add it before on the accept property:
var dropZone3 = new Dropzone("#file3", {
url: "upload.php",
init: function () {
this.on('success', function (file) {
console.log(file);
})
},
accept: function(file, done) {
file.test = "test";
return done();
},
paramName: 'file3',
autoProcessQueue: true,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: 3,
maxFilesize: 5,
addRemoveLinks: true
});

Can't upload files above 1mb in Dropzone

I used Dropzone to handle the file uploads in my Symfony2 project.
It's working fine if I upload files below 1mb but when I upload a file exceeding 1mb, it throws an exception.
I thought the problem was on the maxFilesize config of Dropzone but it wasn't. It was working since it shows a message that the file size exceeds the max size that I've set.
My form:
<form id="quickUpload" action="{{ path('upload_process') }}" method="put" enctype="multipart/form-data" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
Javascript:
Dropzone.options.quickUpload = {
addRemoveLinks: true,
dictDefaultMessage: "Drop files to upload (or click)",
maxFilesize: 5,
init: function () {
this.on("success", function (file, response) {
file.serverId = response.id;
});
this.on("removedfile", function (file) {
if (!file.serverId) {
return;
}
var url = "{{ path("delete_upload") }}";
$.ajax({
url: url,
type: 'POST',
data: {id: file.serverId},
dataType: 'json',
success: function (data) {
console.log("File Deleted");
},
error: function () {
console.log("File Delete Error");
}
});
});
}
}
Controller:
/**
* #Route("/upload_process", name="upload_process")
* #Method("PUT")
*/
public function uploadProcessAction(Request $request) {
if ($request->isXmlHttpRequest()) {
$files = $request->files;
$em = $this->getDoctrine()->getManager();
$ids = [];
foreach ($files as $file) {
$document = new Document();
$document->setUploader($this->getUser())
->setFile($file);
$em->persist($document);
$ids[] = $document;
}
$em->flush();
return new JsonResponse(['id' => $ids[0]->getId()]);
}
}
Finally fixed it. I just needed to change the value of the upload_max_filesize in my php.ini file. I saved the file, restarted XAMPP and got it working.

how to send post data to the server side using uploadify

here is the my javascript code.
$(document).ready(function() {
$("#fileUpload2").fileUpload({
'method' : 'GET',
'uploader': 'js/uploadify/uploader.swf',
'cancelImg': 'js/uploadify/cancel.png',
'script': 'model/Properties/Manage Properties/add_files.php',
'folder': 'files',
'multi': true,
'buttonText': 'Browse',
'checkScript': 'js/uploadify/check.php',
'displayData': 'speed',
'simUploadLimit': 22,
'OnUploadEvent' : function(dom){
$(dom)('#fileUpload2').uploadifySettings(
'scriptData',
{'ext':$('#osDeed').val(), 'ext2':'bab'}
);
}
});
});
this code only can send static data but not form data i dont know. i am just stuck please help.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//uploadify function
$("#file_upload").uploadify({
'uploader': 'uploadify.swf',
'script': 'uploadify.php',
'cancelImg': 'cancel.png',
'folder': 'photos', //folder where images to be uploaded
'auto': false, // use for auto upload
'multi': true,
'queueSizeLimit': 6,
'buttonImg': 'images/upload.png',
'width': '106',
'height': '33',
'wmode': 'transparent',
'method': 'POST',
'scriptData': {'myid':post_id}, //you can post the id here
'onQueueFull': function(event, queueSizeLimit) {
alert("Please don't put anymore files in me! You can upload " + queueSizeLimit + " files at once");
return false;
},
'onComplete': function(event, ID, fileObj, response, data) {
$("#uploadfiles").append(response+",");
},
'onAllComplete': function(response, data) {
showAll();
}
});
</script>
scriptData is used to send the post_id to the php file
uploadify.php
if (!empty($_FILES)) {
$post_id = $_POST['myid'];
include_once "config.php"; //connect to database
//use this when uploading images into a folder
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$fna = $_FILES['Filedata']['name'];
$targetFile = str_replace('//','/',$targetPath) . $fna;
move_uploaded_file($tempFile,$targetFile);
//folder upload end
$name2 = mysql_real_escape_string($_FILES['Filedata']['name']);
$data2 = mysql_real_escape_string(file_get_contents($_FILES['Filedata']['tmp_name']));
$size2 = intval($_FILES['Filedata']['size']);
$db->query("INSERT INTO tbl_files SET post_id='$post_id', filename='$name2', file_data='$data2'");
}
First thing is you should change your method from 'GET' to 'POST', just like
method = 'post'
You can send any value via post to server side via formData property, and then update it "onUploadStart" event of uploadify
Your final code will look like
$(document).ready(function() {
$("#fileUpload2").uploadify({
'formData': {
'ext': '',
'ext2':''
},
'method' : 'post',
'uploader': 'js/uploadify/uploader.swf',
'cancelImg': 'js/uploadify/cancel.png',
'script': 'model/Properties/Manage Properties/add_files.php',
'multi': true,
'buttonText': 'Browse',
'checkScript': 'js/uploadify/check.php',
'onUploadStart': function (file) {
$('#file_upload').uploadify('settings', 'formData', {'ext': $('#osDeed').val(), 'ext2':'bab'});
},
}
});
});

Categories

Resources