Can't upload files above 1mb in Dropzone - javascript

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.

Related

Laravel 8: AJAX Upload files using onchange

I want to upload multiple files using onchange in laravel 8. is it possible to upload just by onchange? I have this html form. I hope you can help me guys. thanks
<form method="POST" enctype="multipart/form-data" id="upload_form">
#csrf
<input type="file" name="file[]" id="file" multiple >
</form>
this is my Jquery and Ajax Script.
<script>
function uploadfile(){
var formData = new FormData($('#upload_form')[0]);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
url: "{{ route('dropzone-action') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
alert('Image has been uploaded successfully');
}
},
error: function(response){
console.log(response);
$('#image-input-error').text(response.responseJSON.errors.file);
}
});
}
and here is my controller
function action(Request $request){
$request->validate([
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($request->hasFile('file')){
foreach($request->file as $file) {
$completeFileName = $file->getClientOriginalName();
$fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$file->storeAs('uploads', $completeFileName);
}
}
return response()->json('Image uploaded successfully');
}
You can call change method
$("#file").change(function() {
uploadfile();
});
and in validation
$request->validate([
'file.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
and in controller
function action(Request $request){
$request->validate([
'file.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
foreach($request->file as $file) {
if($file!=null){
$completeFileName = $file->getClientOriginalName();
$fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$file->storeAs('uploads', $completeFileName);
}
}
return response()->json('Image uploaded successfully');
}

CodeIgniter file upload error “You did not select a file to upload” using Ajax

I've seen and tried a few answers that are similar to this question, but it still displays the same error.
The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)
My view:
<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="fldFileName" class="col-sm-4 control-label">Image</label>
<div class="col-sm-8">
<input type="file" name="fldFileName" value="" class="form-control" id="fldFileName" />
</div>
</div>
<button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>
javascript to submit form:
$(document).on("click", "#newSensorSubmit", function(event){
var posturl="<?php echo site_url("sensors/add_deployment");?>";
var formData = new FormData();
var fldFileName = $('#fldFileName').val();
formData.append('fldFileName', fldFileName);
jQuery.ajax({
url: posturl,
data: formData,
cache: false,
mimeType: "multipart/form-data",
dataType: 'json',
contentType: false,
processData: false,
type: 'POST',
success: function(data){
if(data.status === 'success') {
//handle success
}
else {
//handle fail
}
},
error: (error) => {
$('#articleErrorText').html(JSON.stringify(error));
}
});
});
controller:
public function add_deployment(){
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
$config = array(
'upload_path' => site_url("attachments/project/999/metstations"),
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "16000000"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('fldFileName'))
{
$data['image_metadata'] = array('image_metadata' => $this->upload->data());
}
else
{
$error = $this->upload->display_errors();
$data['errors']='<p class="error-message">'.$error.'</p>';
$data['status']='failure';
}
}
Try This.
To get all your form inputs, including the type="file" you need to use FormData object.
To append param just use append() method:
formData.append("param", "value");
And in the php-side I catch it:
echo $file_name = ($_FILES['file']['name']);
View Code:-
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
jQuery / Ajax Code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'ControllerName/upload_file', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
Controller Code:-
class ControllerName extends CI_Controller {
function __construct() {
parent::__construct();
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE; // remove it for actual file name.
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
}
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

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 Multiple File upload not working For Excel File

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

upload image using formdata ajax send to php

I newbie in this webpage area and I was try to upload image to my file by using ajax and send it to php. But I have done some coding here. Can some one correct me where I'am wrong ?
here is my form with file upload and a button
<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="images" id="images" multiple="" />
<input type="submit" value="submit" id="harlo">
</form>
Once I click on button the file will send it here and receive the src and ajax to php file
but I guess is about getting source problem. Need some one correct it for me.
(function upload() {
var input2 = document.getElementById("harlo"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input2.addEventListener("click", function () {
var i = 0, len = $('input[type="file"]')[0].files;
for ( ; i < len.length; i++ ) {
file = len.files[i];
if (formdata) {
formdata.append("images", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
}());
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
Use something like:
$("form").on("submit", function(
// Your ajax request goes here
$.ajax({
url: "upload.php",
type: "POST",
data: $("form").serialize(),
processData: false,
contentType: false,
success: function (res) {
$("#response").innerHTML = res;
}
});
return false;
));
But there seems to be a problem with sending files trough ajax anyway. Cause they're missed by the serialize() method because JS has no access to files content on users computer. So the form must be sent to the server to get the file data.
See here: https://stackoverflow.com/a/4545089/1652031

Categories

Resources