I am trying to use Dropzonejs to upload music and video files, when I tried it with image files it worked fine, the upload was successful, on trying it with video and music files it gives this error:
Warning post content of ------- bytes exceeds the limit of --------
I have set the configuration for dropzone but it seems not to solve this problem. Because I’m working with Laravel, I edited php_ini file of xampp, to increase the max_file_size and some other parameters, that did not solve the problem either.
Since I’m running Laravel-5.3, it’s evident it might have its own internal server because whether I’m running Xampp or not once I start Laravel server it runs with or without starting apache on Xampp. What do I do?
<div class="row">
<div class="col-md-12">
<form action="{{ url('/songs/do-upload') }}" class="dropzone" id="addSongs">{{csrf_field()}}
<input type="hidden" name="albums_id" value=" {{$albums->id}} ">
</form>
</div>
</div>
<script type="text/javascript">
Dropzone.options.addSongs = {
paramName: 'file',
clickable: true,
enqueueForUpload: true,
autoProcessQueue: true,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 1,
maxFilesize: 250,
addRemoveLinks: true,
dictDefaultMessage: 'Drag your images here',
init: function() {
console.log('init');
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
this.removeFile(file);
});
}
};
</script>
Controller used in uploading:
public function doImageUpload(Request $request){
$file = $request->file('file');
$fileName = uniqid() .$file->getClientOriginalName();
$file->move('album/songs', $fileName);
$albums = Albums::findOrFail($request->input('albums_id'));
$album = $albums->songs()->create([
'user_id' => Auth::user()->id,
'albums_id' => $request->input('albums_id'),
'file_name' => $fileName,
'file_size' => $file->getClientSize(),
'file_mime' => $file->getClientMimeType(),
'file_path' => 'album/songs' .$fileName
]);
}
Error message on the console:
1:107 Uncaught ReferenceError: Dropzone is not defined
http://localhost:8000/songs/do-upload Failed to load resource: the server responded with a status of 500 (Internal Server Error)
jquery-1.9.0.js:1'//# sourceURL' and '//# sourceMappingURL' are deprecated, please use '//# sourceURL=' and '//# sourceMappingURL=' instead.
Thanks, everyone. The simple mistake was that I didn't restart the Laravel server. Appreciate.
Related
I am trying to use the snappy library with wkhtmltopdf to render a chart (LavaChart) on a generated PDF but I have not been able. The PDF generates fine but the chart does not show. If the view is not converted to PDF, the Chart is rendered as expected.
Below is my code for the LavaChart and Snappy.
The Chart Part
$chart = Lava::ColumnChart('Performance', $table, [
'title' => 'Performance Chart',
'png' => true,
'animation' => [
'startup' => true,
'easing' => 'inAndOut'
],
'titleTextStyle' => [
'fontName' => 'Arial',
'fontColor' => 'blue'
],
'legend' => [
'position' => 'top'
],
'vAxis' => [
'title' => 'Total Score'
],
'hAxis' => [
'title' => 'Class'
],
'events' => [
'ready' => 'getImageCallback'
],
'colors' => ['#3366CC','#DC2912', '#FF9900']
]);
The Snappy Part
$pdf = PDF::loadView('print.charts')->setPaper('portrait');
$pdf->setOption('enable-javascript', true);
$pdf->setOption('javascript-delay', 10000);
$pdf->setOption('no-stop-slow-scripts', true);
$pdf->setOption('page-size', 'A4');
$pdf->setOption('margin-left', 0);
$pdf->setOption('margin-right', 0);
$pdf->setOption('margin-top', 0);
$pdf->setOption('margin-bottom', 0);
$pdf->setOption('lowquality', false);
$pdf->setTimeout(1500);
$pdf->setOption('disable-smart-shrinking', true);
The View Part
<script type="text/javascript">
function getImageCallback (event, chart) {
console.log(chart.getImageURI());
}
</script>
<div id="chart" style="margin: 10px; height: 200px; width: 50%;"></div>
{!! Lava::render('ColumnChart', 'Performance', 'chart') !!}
Since the chart renders as expected when the view is not converted to pdf, I have reasons to believe the wkhtmltopdf does not execute the javascript has expected in the pdf version. I have the latest wkhtmltopdfinstalled but still no luck.
Library Version:
barryvdh/laravel-snappy: ^0.4.3
khill/lavacharts: 3.0.*
Any help will be appreciated, thanks.
I can show with a simple example, At first I have shown the chart on browser, The chart example is taken from Lavacharts docs(you can use yours). Keep a Note on
events with callback getImageCallback.
public function index(){
$lava = new Lavacharts;
$data = $lava->DataTable();
$data->addDateColumn('Day of Month')
->addNumberColumn('Projected')
->addNumberColumn('Official');
// Random Data For Example
for ($a = 1; $a < 20; $a++) {
$rowData = [
"2020-10-$a", rand(800,1000), rand(800,1000)
];
$data->addRow($rowData);
}
$lava->LineChart('Stocks', $data, [
'elementId' => 'stocks-div',
'title' => 'Stock Market Trends',
'animation' => [
'startup' => true,
'easing' => 'inAndOut'
],
'colors' => ['blue', '#F4C1D8'],
'events' => [
'ready' => 'getImageCallback'
]
]);
return view('charts-view', ['lava' => $lava]);
}
In view charts-view,
<div id="stocks-div">
<?= $lava->render('LineChart', 'Stocks', 'stocks-div'); ?>
</div>
<form action="{{ url('export-pdf') }}" method="post">
#csrf
<div class="form-group">
<input type="hidden" name="exportpdf" id="exportPDF">
<button class="btn btn-info" type="submit">Export as PDF</button>
</div>
</form>
<script type="text/javascript">
function getImageCallback (event, chart) {
console.log(chart.getImageURI());
document.getElementById("exportPDF").value = chart.getImageURI();
}
</script>
note the function name in script must be same as the value set for ready key in events in the controller. Upto this step you have done as well. I have passed the result obtained by as a hidden input field and posted the form to the controller.You can see in the diagram button export as PDF.
The url export-pdf calls the controller function exportPdf which willfinally generate the PDF. You need to pass the image (obtained as data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB .....) to the controller to pass it to the view as image.
In exportPdf,
public function exportPdf(Request $request){
$imageData = $request->get('exportpdf');
$pdf = SnappyPDF::loadView('export-pdf', ['imageData' => $imageData])->setPaper('a4')->setOrientation('portrait');
$pdf->setOption('lowquality', false);
$pdf->setTimeout(1500);
$pdf->setOption('disable-smart-shrinking', true);
return $pdf->download('stock-market.pdf');
}
The export-pdf blade view
<!DOCTYPE html>
<html lang="en">
<head>
<title>Stock Market</title>
</head>
<body>
<div class="container">
<div class="col">
<h2>Stock Market Detail</h2>
</div>
<div class="col">
<h4>Oct 2020</h4>
</div>
</div>
<img src="{{ $imageData }}" alt="image" width="720" height="230">
</body>
</html>
The final PDF obtained looks like,
I have a page that allows users to edit a property listing they had previously submitted. I've been using bootstrap-fileinput to allow users to add images, and it will use the initialPreview attribute to show images that they've already uploaded. Users can remove the initialPreview images to remove images from the dropzone, but I can't find a way to pass this info to the server, that the user has removed these initialPreview images.
I've tried uploadExtraData: function() {}
But I can't get any information about the initialPreview images. Also, I am using the Laravel 5.7 PHP framework for my website.
<div class="form-group">
<label for="additional_info" class="col-lg-12 control-label">Add Photos to Attract Lender Interest</label>
<div class="col-lg-12">
<input type="file" name="image[]" id="image" multiple class="image" data-overwrite-initial="false"
data-min-file-count="0" value="{{ $mortgage->close_date}}">
</div>
</div>
{{-- Scripts for the pretty file input plugin called bootstrap-fileinput --}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.4.7/js/fileinput.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/4.5.2/themes/fas/theme.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#image").fileinput({
overwriteInitial: false,
initialPreview: [
// IMAGE DATA
"http://digitalbroker.test/storage/properties/847%20Queen%20Street%20West,%20Toronto,%20ON,%20Canada_1.JPG",
// IMAGE DATA
"http://digitalbroker.test/storage/properties/847%20Queen%20Street%20West,%20Toronto,%20ON,%20Canada_2.JPG",
],
initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
initialPreviewFileType: 'image', // image is the default and can be overridden in config below
initialPreviewDownloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/{filename}', // includes the dynamic `filename` tag to be replaced for each config
showUpload: false,
theme: 'fas',
uploadUrl: "/submit-mortgage",
uploadExtraData: function () {
return {
_token: $("input[name='_token']").val(),
};
},
allowedFileExtensions: ['jpg', 'png', 'gif', 'jpeg'],
overwriteInitial: true,
showCaption: false,
showRemove: true,
maxFileSize: 5000,
maxFilesNum: 8,
fileActionSettings: {
showRemove: true,
showUpload: false,
showZoom: true,
showDrag: false,
},
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
</script>
Right now it just removes any old images upon submit and will save any newly uploaded ones. I'd like to both keep track of what initialPreview images were not removed, and which new images were uploaded.
I know this is an older question, but for those who stumble upon it here is a solution:
When a user clicks the remove button on the initialPreview frame you can pass information from that to the server by adding additional option to fileinput which will make an Ajax call each time the remove button is clicked.
Using the question above you would need to add:
initialPreviewConfig: [
{
// This is passed to the server in the request body as key: 0
key: 0,
// This is the url that you would send a POST request to that will handle the call.
url: 'http://www.example.com/image/remove',
// Any extra data that you would like to add to the POST request
extra: {
key: value
}
}
]
You would need to create an object for each item you have within your initialPreview array.
The OP's .fileinput would become:
$("#image").fileinput({
overwriteInitial: false,
initialPreview: [
// IMAGE DATA
"http://digitalbroker.test/storage/properties/847%20Queen%20Street%20West,%20Toronto,%20ON,%20Canada_1.JPG",
// IMAGE DATA
"http://digitalbroker.test/storage/properties/847%20Queen%20Street%20West,%20Toronto,%20ON,%20Canada_2.JPG",
],
initialPreviewConfig: [
{
key: 0,
url: '/image/remove', //custom URL
extra: {
image: '847 Queen Street West, Toronto, ON, Canada_1.JPG
}
},
{
key: 1,
url: '/image/remove', //custom URL
extra: {
image: 847 Queen Street West, Toronto, ON, Canada_2.JPG
}
},
],
initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
initialPreviewFileType: 'image', // image is the default and can be overridden in config below
initialPreviewDownloadUrl: 'http://kartik-v.github.io/bootstrap-fileinput-samples/samples/{filename}', // includes the dynamic `filename` tag to be replaced for each config
showUpload: false,
theme: 'fas',
uploadUrl: "/submit-mortgage",
uploadExtraData: function () {
return {
_token: $("input[name='_token']").val(),
};
},
allowedFileExtensions: ['jpg', 'png', 'gif', 'jpeg'],
overwriteInitial: true,
showCaption: false,
showRemove: true,
maxFileSize: 5000,
maxFilesNum: 8,
fileActionSettings: {
showRemove: true,
showUpload: false,
showZoom: true,
showDrag: false,
},
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
I hope this helps anybody who comes across it.
FYI this is my first answer on SO (please be kind :P )
I have implemented dropzone drag and drop for upload image with Laravel which working fine in my localhost. But when I uploaded it to my ubuntu server it's not uploading images but showing 500 internal server error in browser console.
Here is my view file code...
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
<div>
<h5 style="text-align: center;">Drag and Drop or Click to Upload Product Images</h5>
</div>
{!! Form::close() !!}
Here is the javascript...
var jsarray = [];
Dropzone.options.imageUpload = {
maxFilesize : 8,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
success: function(file, response){
console.log(response.success);
}
};
Route:
Route::get('dropzone', 'ImageController#dropzone');
Route::post('dropzone/store',['as'=>'dropzone.store','uses'=>'ImageController#dropzoneStore']);
Controller:
public function dropzoneStore(Request $request)
{
$image = $request->file('file');
$imageName = time().$image->getClientOriginalName();
$path = "images";
$image->move($path,$imageName);
return response()->json(['success'=>$imageName]);
}
Error in browser console:
POST http://finance.technozone.com.au/finance/dropzone/store 500 (Internal Server Error)
Please anybody help me to solve my problem.....
I get "CLI stopped working" error when i press the upload button.I used the sample code from one of the website to upload file into the database column. I use Laravel 5.2.39. command used: php artisan serve
Code:(Only test version)
Form.blade.php
<form method="post" enctype="multipart/form-data" action="/upload_file">
{{ csrf_field() }}
<input type="file" name="file" />
<input type="submit" name="submit" value="upload" />
</form>
Routes.php
(Not an ideal place to code this but it is only for file upload test purpose)
Route::get('/upload_form', function()
{
$data['files'] = Attachment::get();
return View::make('form', $data);
});
Route::post('/upload_file', function()
{
$rules = array(
'file' => 'required|mimes:doc,docx,pdf',
);
$validator = Validator::make(Request::all(), $rules);
if(Request::hasFile('file'))
{
$f = Request::file('file');
$att = new Attachment;
$att->name = $f->getClientOriginalName();
$att->file = base64_encode(file_get_contents($f->getRealPath()));
$att->mime = $f->getMimeType();
$att->size = $f->getSize();
$att->save();
return Redirect::to('/upload_form');
}
});
Has anyone encountered this issue? Need help.
I'm having trouble with validation on this AJAX POST for a file upload. Here's what I have so far. The 'required' validation keeps coming back telling me to select an image. When I console.log() the js variable with the image, it shows the filepath correctly.
View:
<form role="form" method="post" action="{{ route('profile.edit') }}" enctype="multipart/form-data">
<div class="form-group new-pic{{ $errors->has('profile-image') ? ' has-error' : '' }}">
<input type="file" id="newProfilePic" name="profile-image"/>
</div>
</form>
JS:
$('.btn-edit-profile-pic').click(function(e){
e.preventDefault();
var newPic = $('#newProfilePic').val();
$.ajax({
type: "POST",
url: "/profile-edit",
data: newPic,
error: function(data) {
var errors = $.parseJSON(data.responseText);
console.log(errors);
},
success: function() {
}
});
});
Controller:
if ($request->ajax())
{
$this->validate($request, [
'newPic' => 'required|image|max:4999'
],[
'required' => 'You must select an image',
'image' => 'The file must be an image',
'max' => 'The image file size must be less than 5mb'
]);
$extension = Input::file('profile-image')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension;
$image = Image::make(Input::file('profile-image'))
->orientate()
->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
})
->save('images/profiles/'.$fileName);
Auth::user()->update([
'image_path' => $fileName,
]);
}
this is an intended behavior, you cant send upload file over XMLHTTPRequest, that is why you will always received the image file is required validation.
you can use an ajaxfileuploader plugins (They create a new form with in an iframe and submit it)
[http://www.sitepoint.com/10-jquery-ajax-file-uploader-plugins/]