I can upload the files if they are fitting this validation rule
'user_file' => 'file|max:10240|mimes:xls,xlsx,doc,docx,pdf,zip'
all goes fine.
I have set my upload_max_filesize to 32MB and post_max_size to 40MB in php.ini
but if i try to upload a file bigger than 40MB my validation rules don't even trigger. I get TokenMismatchException error....
If someone can verify this by simply trying to upload some very big file (a video file for example)
When You exceed post payload size - everything is dropped, so csrf_token does not come to laravel and the upload file is empty so it cannot be validated.
UPDATE
To fix this you need to check the file size before the uploading with javascript or jquery
here is an example:
How to check file input size with jQuery?
In the case of file uploads, the file has to be copied to temp location into the server then the rules will work. so your server will not allow files of size greater than 40MB (post_max_size) into the temp location so rules will not work.
Instead, to fix this you need to do frontend validation for files.
You can do this using simple Javascript as shown below,
$('input[type="file"]').change(function () {
if (this.files[0] != undefined) {
var name = this.name;
var filesize = this.files[0].size;
var field = $('#' + this.name).parents('.input-group');
//check if file size is larger than 3MB(which is 3e+6 bytes)
if (filesize > 3000000) {
alert(filesize);
//reset that input field if its file size is more than 3MB
$('[name="' + name + '"]').val('')
}
}
});
you can just include this for all input of type='file' by changing size limit in bytes.
I encountered the same problem. You should as well check that the validator is checking file data, not post data :
I've tested :
$validator = Validator::make($request->post(), [
myfield' => 'required|image|mimes:jpeg,png,jpg,gif|max:1000000'
]);
Should have been :
$validator = Validator::make($request->file(), [
myfield' => 'required|image|mimes:jpeg,png,jpg,gif|max:1000000'
]);
Related
I'm using Codeigniter, i have a problem when uploading too large images, i.e. the size of the image is larger than upload_max_filesize in the server.
I would like to show a custom message for the user instead of this message:
Warning: POST Content-Length of 36276449 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
The action you have requested is not allowed.
You have to validate, while uploading image to the server, if the image size is below some MB then allow to upload on the server otherwise throw the validation error.
You can use jQuery validate plugin to do that here is the reference you can use it.
Validate file extension and size before submitting form
Maybe (if you are the server admin) you can increase the maximun post size (Increasing the maximum post size) and then check the size and show the message through codeigniter:
$config['max_size'] = 100;
...
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile'))
{
//handle the error with $this->upload->display_errors()
}
I've setup an Angular based file upload using the ng-file-upload plugin (https://github.com/danialfarid/ng-file-upload) and I've been handling the file upload with a PHP script.
The file upload and script work on smaller files (tested it on < 1MB), but fails on a larger file (9MB). This leads me to believe that there's a file upload issue. However, I've already created a .user.ini file in the /wwwroot folder with a single line:
upload_max_filesize=20M
Is there another reason why the $_FILES and $_POST arrays would be empty?
JS Code:
Upload.upload({
url: '/scripts/receiveFile.php',
file: file
}).then(function(resp) {
console.log(resp.data);
}, function(resp) {
console.log(resp.data);
}, function(evt) {
var progressPercent = parseInt(100.0 * evt.loaded / evt.total);
console.log(progressPercent + "%");
});
HTML Code:
<div>
<h1>Upload</h1>
<input type="file" accept=".zip" ngf-select="submitFile($file)"></input>
</div>
PHP Code:
$file_name = basename($_FILES['file']['name']);
$file_tmp_name = $_FILES['file']['tmp_name'];
The script fails because 'file' is undefined in the $_FILES array - because the $_FILES array is empty.
Thanks!
PHP has a confusing was of doing file uploads. To set a larger upload size, you should set both upload_max_filesize and post_max_size. These can be independently different values, as they do different things.
post_max_size is the maximum file size that can be sent in a POST request to the PHP script. upload_max_filesize is the maximum file size allowed via any method.
I really hope someone can help me with this issue as I've tried everything I know.
The Issue:
Dropzone doesn't upload any images above 3mb instead shows 422 (Unprocessable Entity), images bellow 3mb upload perfectly fine. I've tried everything possible as well as spent plenty of time searching Google, I am receiving the issue both on local machine (Mac OSX using MAMP pro) and on my linux server (ubuntu 14.0). I believe this may be either a laravel or dropzone issue that I cant seem to figure out.
The File I'm trying to upload is straight from a cannon cam, 8mb filenames date+time.JPG, Ive checking the files via saving them as different outputs .jpg, .jpeg, .png however it still fails, they do work if I save them for web and optimize bellow 3mb however I need to be able to upload at least 9mb.
PHP Ini Settings:
upload_max_filesize = 30M
post_max_size = 30M
Form Settings:
Standard laravel open form with crftoken (_token)
DropZone Settings:
Dropzone.options.templateDrop = {
maxFilesize: 30,
maxThumbnailFilesize:15,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
init: function () {
this.on("addedfile", function (file) {
//Show loader whilst uploading
$('.jqueryLoader').show();
});
this.on("complete", function (file) {
//when images are fully uploaded reset div and functions within
if (this.getUploadingFiles().length == 0 && this.getQueuedFiles().length == 0) {
$('#galleryImageHolder').load(document.URL + ' #galleryImageHolder', function(){
galleryFunctions();
$('.jqueryLoader').hide();
});
}
});
}
};
Thanks in advance for any help you can offer.
Kind Regards,
Martyn
Are you doing any server-side validation in Laravel? For example, my Upload Request sets a maximum file size on an upload:
public function rules()
{
$rules = [
'file' => 'max:2048'
];
return $rules;
}
We are currently trying to use the extension eajaxupload for Yii but it seems to be outputting failed everytime we try to upload a file.
We have tried
a) editing the file / minimum file sizes
b) playing around with the file path (may still be incorrect, if anyone knows what the path for locally using in xampp would be, let us know. Our uploads folder is in the root of the project.)
c) changing the htiaccess php file
d) permissions
we just don't know if the code itself is appearing wrong.
controller
/* UPLOADER */
public function actionUpload(){
Yii::import("ext.EAjaxUpload.qqFileUploader");
// $folder = '/uploads/';
// $folder=Yii::getPathOfAlias() .'/upload/';
$folder=Yii::app()->baseUrl . '/uploads/';
$allowedExtensions = array("jpg","png");//array("jpg","jpeg","gif","exe","mov" and etc...
$sizeLimit = 10 * 1024 * 1024;// maximum file size in bytes
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload($folder);
// $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
//
// $fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
// $fileName=$result['filename'];//GETTING FILE NAME
//
// echo $return;// it's array
$result = $uploader->handleUpload($folder);
$fileSize=filesize($folder.$result['filename']);//GETTING FILE SIZE
$fileName=$result['filename'];//GETTING FILE NAME
$result=htmlspecialchars(json_encode($result), ENT_NOQUOTES);
echo $result;// it's array
}
View
*$this->widget('ext.EAjaxUpload.EAjaxUpload',
array(
'id'=>'uploadFile',
'config'=>array(
'action'=>'/upload/',
// 'action'=>Yii::app()->createUrl('controllers/uploads/'),
'allowedExtensions'=>array("jpg","png"),//array("jpg","jpeg","gif","exe","mov" and etc...
'sizeLimit'=>10*1024*1024,// maximum file size in bytes
//'minSizeLimit'=>10*1024*1024,// minimum file size in bytes
'onComplete'=>"js:function(id, fileName, responseJSON){ alert(fileName); }",
'messages'=>array(
'typeError'=>"{file} has invalid extension. Only {extensions} are allowed.",
'sizeError'=>"{file} is too large, maximum file size is {sizeLimit}.",
'minSizeError'=>"{file} is too small, minimum file size is {minSizeLimit}.",
'emptyError'=>"{file} is empty, please select files again without it.",
'onLeave'=>"The files are being uploaded, if you leave now the upload will be cancelled."
),
'showMessage'=>"js:function(message){ alert(message); }"
)*
I got the same problem long ago.
You have to make sure that:
you get the local path, not url (Yii::getPathOfAlias('webroot')).
the $sizeLimit has to be less than the php options 'post_max_size' and 'upload_max_size'. You can check their values with ini_get(variable) and convert it to Bytes.
Also noticed that you are trying to upload the file twice.
If none of them work post the error message that you are getting.
It seems to me that your action is wrong in the
'config'=>array(
'action'=>'/upload/',
If you are uploading to the public function actionUpload()
then your action must be 'upload/upload' because the ConrollerName/ActionName must match the 'action' in your widget
'config'=>array(
'action'=> Yii::app()->baseUrl . '/upload/upload',
or
'config'=>array(
'action'=>$this->createUrl('upload/upload')
Take a look at this too: http://www.yiiframework.com/doc/guide/1.1/en/topics.url
Good luck
To update this, it wouldn't work on local server Xampp on MAC.
It worked on our live dev server, but not the live server. Seems the extension is server dependant. There is a lack of documentation and I imagine there is a fix, but it answers a lot of questions how the code is fine but not working.
I have a file uploading function on my Symfony2 project.
I am seting the maxSize parameter like that:
$manuscript_file = new File(array(
'maxSize' => '20M',
'mimeTypes' => array(
'application/msword',
'application/zip',
),
'mimeTypesMessage' => 'Please upload a valid manuscript file. Valid types are: doc, docx, zip',
));
The problem is that when I am trying to upload a 2M or 3M word file, I am getting the validation message:
The file is too large. Allowed maximum size is 20M bytes.
Did you faced that? Or is my code wrong.
I took the example from the Symfony documentation:
Symfony File - Validation Constraints Reference
I already faces this issue, so I post this solution (I think this is the same issue for you).
This is a known bug of Symfony, in fact the framework will display the validator error message also when the file size is too high for your PHP configuration, instead of getting the classical PHP error.
In your current PHP config, you probably limited the max upload size to 2M, so Symfony display the wrong error.
So check your php.ini file (/etc/php5/apache2/php.ini on Linux) and increase max_upload_size to fit your field :
upload_max_filesize = 20M
Don't forget to restart apache : apache2ctl restart
Now it should work !
Note that's probably fixed on the last Symfony version, another solution is perhaps to upgrade your project to sf2.3 (but i'm not sure of that) ^^
I created a jQuery validation method to prevent sending big files to server because php don't valide it (It is in Spanish):
$(function() {
//Validate 20MB
validarFileSize('#carga_telefonos_form_file', {{ 10*1024*1024 }}, '#div-mensaje-file-size', '#botonSubmit');
});
function validarFileSize(campo, maximo, divMensaje, btnGuardar) {
console.debug("validarFileSize. Campo: " + campo + ", maximo: " + maximo);
$(campo).bind('change', function() {
var size = this.files[0].size;
if (size > maximo) {
$(divMensaje).show();
$(btnGuardar).attr('disabled', 'disabled');
} else {
$(divMensaje).hide();
$(btnGuardar).removeAttr('disabled');
}
});
}
If you are using POST to upload your file, beware with post_max_size limit in php.ini