How can I abort file upload in Plupload? - php

I'm trying to create a gallery plugin for Wordpress and I'm using Plupload to upload some images.
Before user can uploading images for a new gallery, the gallery name must be added. Since I'm using drag and drop, I need to abort the file upload if the gallery name i empty.
I've tried various solution, but I'm not able to stop the file upload (I think).
At the bottom in my SJ script, I'm doing a check on dragover. Where I want to abort is marked with //HERE FILE UPLOAD MUST ABORT.
But I'm not sure if this is the right place. Can anyone tell me where I can abort the upload on dragover (and drop)?
// PHP code - I'm adding this data here, because I need some WP data
function plupload_init() {
//$image_size = get_option('sim_gallery_max_width_height');
$plupload_arr = array(
'runtimes' => 'html5,silverlight,flash,html4,browserplus,gears',
'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
'container' => 'plupload-upload-ui', // will be adjusted per uploader
'drop_element' => 'drag-drop-area', // will be adjusted per uploader
'file_data_name' => 'async-upload', // will be adjusted per uploader
'multiple_queues' => true,
'max_file_size' => wp_max_upload_size() . 'b',
'url' => admin_url('admin-ajax.php'),
'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
'filters' => array(array('title' => __('Image files'), 'extensions' => 'jpg,jpeg,gif,png')),
'multipart' => true,
'urlstream_upload' => true,
'multi_selection' => false, // will be added per uploader
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => "", // will be added per uploader
'action' => 'plupload_action', // the ajax action name
'imgid' => 0 // will be added per uploader
)
);
?>
<script type="text/javascript">
var plupload_config_vars = <?php echo json_encode($plupload_arr); ?>;
</script>
<?php
}
// JS scrip
function init_image_upload() {
if(jQuery('#image-upload').length == 0)
return;
var plupload_config = JSON.parse(JSON.stringify(plupload_config_vars));
var uploader = new plupload.Uploader(plupload_config);
// Control gallery name
control_gallery_name();
uploader.bind('Init', function(up){});
uploader.init();
// a file was added in the queue
uploader.bind('FilesAdded', function(up, files){
});
// Change border color on drop zone
function drop_area_visual_feedback(up) {
var uploaddiv = jQuery('#plupload-upload-ui');
if ( up.features.dragdrop) {
uploaddiv.addClass('drag-drop');
jQuery('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
if(!jQuery('input[name="gallery-name"]').val()) {
jQuery('label.missing-name').removeClass('hidden');
//HERE FILE UPLOAD MUST ABORT
} else {
uploaddiv.addClass('drag-over');
}
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
jQuery('#drag-drop-area').unbind('.wp-uploader');
}
}
}

Have you tried putting your code in the FilesAdded handler, like this ?
// a file was added in the queue
uploader.bind('FilesAdded', function(up, files){
if(!jQuery('input[name="gallery-name"]').val()) {
jQuery('label.missing-name').removeClass('hidden');
up.splice(0);
}
});

Related

In the model, click on the button to download the pdf file, But not working (Laravel)

I have products. Products have 1product(model).If user click button download pdf in model. I create function create pdf but not working.
Pdf Generator function in this controller
public static function pdf_g(){
// HTML
$html = '<h1>This html</h1>';
// CREATE NEW PDF
$mpdf = new Mpdf();
// WRITE HTML
$mpdf->WriteHTML($html);
// DEST: D - DOWNLOAD
return $mpdf->Output('asd.pdf', 'D');
}
Controller SEND RESPONSE->JSON mpdf
public function show_cadastre(Folder $folder,Cadastre $cadastre){
// GET THIS CADASTRE ID VALDOS
$get_valdos = Valdos_matmenys::where('KAD_ID', $cadastre->ID)->first();
// GET VISAS_PLOTAS
$visas_plotas = round($get_valdos->PLOTAS_K / 10000, 2);
// GET MISKO
$misko = round($get_valdos->MISK / 10000, 2);
// GET Vandens plotas
$vandens = round($get_valdos->PLOTAS_V / 10000, 2) ;
// GET KITO PLOTO
$kito_ploto = round($visas_plotas - ($misko + $vandens), 2);
// GET Girininkija
$girininkija = $cadastre->GIRININKIJ;
// GET Apskirtis
$apskirtis = Savivaldybe::where('SAV_ID', $cadastre->SAV_ID)->first();
$apskirtis_pav = $apskirtis->apskritis;
// GET Uredija
$uredija = Uredija::where('ured', $cadastre->ured)->first();
$ured_pavadinimas = $uredija->pavadinimas;
// GET Rajonas
$raj = Cadastre::getRagion($cadastre->RAJ);
// GET MAP
$mapUrl = Cadastre::GenerateMap($cadastre->NTR_ID, array('style' => 'ORTOFOTO_TIK_VALDA', 'offsetRatio' => 0.3))[0];
// GET BACKGROUND
$backgroundUrl = Cadastre::GenerateMap($cadastre->NTR_ID, array('style' => 'ORTOFOTO_TIK_VALDA', 'offsetRatio' => 0.3))[1];
// CREATE PDF FOR Zemelapis is virsaus
// PDF DOWNLOAD
$mpdf = self::pdf_g();
return response()->json(array(
'cadastre' => $cadastre,
'visas_plotas' => $visas_plotas,
'misko' => $misko,
'vandens' => $vandens,
'kito_ploto' => $kito_ploto,
'girininkija' => $girininkija,
'apskirtis_pav' => $apskirtis_pav,
'ured_pavadinimas' => $ured_pavadinimas,
'raj' => $raj,
'mapUrl' => $mapUrl,
'backgroundUrl' => $backgroundUrl,
'mpdf' => $mpdf
));
}
Html button (this button is in the model)
<a id="pdfMapFromTop" class="text-center text-decoration-none text-smooth-dark p-1">
<span class="align-self-center">
<i class="fa fa-file-pdf text-danger"></i>
</span>
<span class="text-default-dark small align-self-center d-inline-flex flex-column">Žemėlapis_iš_viršaus.pdf</span>
</a>
Jquery model show.
$.ajax({
type: "GET",
crossDomain: true,
url: '/dashboard/folder/' + folder_id + '/cadastre/' + cadastre_id,
success: function (data) {
console.log(data)
// KODASTRINES NUMERIS
$('#ID').text(data.cadastre.ID);
// get visas_plotas
$('#visas_plotas').text(data.visas_plotas + 'ha');
// get misko
$('#misko').text(data.misko + 'ha');
// get vandens
$('#vandens').text(data.vandens + 'ha');
// get kito_ploto
$('#kito_ploto').text(data.kito_ploto + 'ha');
// get girininkija
$('#girininkija').text(data.girininkija);
// get apskirtis
$('#apskirtis').text(data.apskirtis_pav);
// get uredija
$('#uredija').text(data.ured_pavadinimas);
// get rajonas
$('#rajonas').text(data.raj);
// get map url (img)
$('#mapUrl').attr('src', data.mapUrl);
// get map backgroundUrL (img)
$('#backgroundUrl').attr('src', data.backgroundUrl);
// If click this button download pdf
$('#pdfMapFromTop').on('click', function () {
return data.mpdf;
})
// Show this model
$('#show-cadastre-model-xl').modal('show');
},
// error: function (error) {
// console.log(error);
// }
});
The problem is when I click to open the model. Shows such incomprehensible text in the console.
Help please! Thanks all!!!!
this is your raw pdf data!
all you need is to load it to a blade
look at here
$license = license::findOrFail($id);
$data = [
'license' => $license,
'user' => Auth::user(),
'labels' => LicValues::where('license_id',$id)->get()
];
return PDF::loadView('print', $data)->download('print.pdf');
i wrote this couple weeks ago .dont know its your package or not but solution is same
i loaded my data in blade called print and then download it as pdf
read your package documentaion and issues you will find your solution
Looks like your response doesn't have necessary headers. Tell browser, that the response is PDF and it should be downloaded. You are passing text/html here.
Pass this:
Content-type:application/pdf
Check this:
correct PHP headers for pdf file download
Bonus:
This is the best method to generate/store/download the PDFs.
The DOMPDF Laravel wrapper.
https://github.com/barryvdh/laravel-dompdf

Laravel get mimeType from uploaded image

I am using jQuery file uploader to upload a resized image, convert it to blob and save it as blob into a DB.
For the database I also need to save the mimeType, which I see in the request, which I receive, but I dont understand how to get the mimeType value.
The code to send the image:
var formData = new FormData();
formData.append("_token", $('meta[name="csrf-token"]').attr('content'));
formData.append("user_id_val", $('.user-general-i').data('userid'));
// HTML file input, chosen by user
formData.append("userfile", data.files[0]);
var request = new XMLHttpRequest();
request.open("POST", "http://localhost.eu/home/create_comment_images");
request.onload = function(oEvent) {
if (request.status == 200) {
console.log('success');
} else {
console.log(request.status);
}
};
request.send(formData);
Code on the server:
public function create_comment_images(Request $data) {
\Log::info($data);
try {
$path = $data->userfile;
$logo = file_get_contents($path);
$base64 = base64_encode($logo);
return ['success' => true];
} catch (\Exception $e) {
return ['success' => false, 'message' => $e->getMessage()];
}
return ['success' => false, 'message' => 'Something went wrong'];
}
The log info shows me this:
array (
'_token' => 'QxOqetFU2Re6fwe442vksGNnvV0C88v8dcrFpAp',
'user_id_val' => '568092',
'userfile' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => 'Unbenannt.png',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
)
I am almost there, I need the get the mimeType information from the array.
I tried:
$data->userfile->mime_content_type
$data->userfile->mimeType
$data->userfile['mimeType']
$data->userfile[0]['mimeType']
Nothing works. Any ideas how to extract that information?
On Laravel you can use the intervention library. This library is very powerfull you can change the format, resize and do all kind of stuff.
Here a basic example..
// read image from temporary file
$img = Image::make($_FILES['image']['tmp_name']);
// get or sets the mime type.
$mimeType = $img::mime();
// save image
$img->save('foo/bar.jpg');
// Get image as string.
$string = base64_encode($img->encode('jpg'));
Intervention Reference
To get the mimetype from the uploaded file header, you can call getMimeType() on the \Illuminate\Http\UploadedFile class.
$uploadedFile = $data->file('userfile');// or
$mimeType = $uploadedFile->getMimeType()

How to active media gallery in custom media uploader WordPress

I make custom media up loader and its working perfectly on a meta field. In my media up loader there is no gallery option. But now I want to give an option for gallery on it. I search a lot and follow their steps but not succeed.
Here is my Code that working perfectly without gallery option:
var meta_image_frame_gallery;
// Runs when the image button is clicked.
jQuery('#additional_image_1').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame_gallery ) {
meta_image_frame_gallery.open();
return;
}
// Sets up the media library frame
meta_image_frame_gallery = wp.media.frames.meta_image_frame_gallery = wp.media({
title: 'Upload Image',
button: { text: 'Upload Image' },
library: { type: 'image' },
});
Runs when an image is selected.
meta_image_frame_gallery.on('select', function(){
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame_gallery.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
jQuery('#itv_additional_image_1').val(media_attachment.url);
});
// Opens the media library frame.
meta_image_frame_gallery.open();
});
And here is my code for gallery option:
var meta_image_frame_gallery;
// Runs when the image button is clicked.
jQuery('#additional_image_1').click(function(e){
// Prevents the default action from occuring.
e.preventDefault();
// If the frame already exists, re-open it.
if ( meta_image_frame_gallery ) {
meta_image_frame_gallery.open();
return;
}
// Sets up the media library frame
meta_image_frame_gallery = wp.media.frames.meta_image_frame_gallery = wp.media({
title: 'Upload Image',
button: { text: 'Upload Image' },
multiple: true,
library: { type: 'image' },
});
// Runs when an image is selected.
//meta_image_frame_gallery.on('select', function(){
//
// // Grabs the attachment selection and creates a JSON representation of the model.
// var media_attachment = meta_image_frame_gallery.state().get('selection').first().toJSON();
//
// // Sends the attachment URL to our custom image input field.
// jQuery('#itv_additional_image_1').val(media_attachment.url);
//});
// When an image is selected, run a callback.
meta_image_frame_gallery.on( 'select', function() {
var selection = meta_image_frame_gallery.state().get('selection');
selection.map( function( attachment ) {
attachment = attachment.toJSON();
// Do something with attachment.id and/or attachment.url here
jQuery('#itv_additional_image_1').val(selection.url);
});
});
// Opens the media library frame.
meta_image_frame_gallery.open();
});
First I want an option for gallery and second when I create a gallery, its short-code will appear on meta field and then i save it in db.
Please any give any guidance that help me out.
I figure it by more searching and found some links check them. Now gallery option is active in my media up loader.
Here is my Code now:
Just add three more params
frame: "post",
state: 'gallery-library',
multiple: true
in this line meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media( {
Complete code:
meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media( {
title: 'My Gallery',
frame: "post",
state: 'gallery-library',
library: {
type: 'image'
},
multiple: true
} );
And now its working perfectly

how to pass php controller file to view php file in jquery function codeigniter

Hi Am new to PHP: i had tried to upload a image file with random generated nos .then i want to return the uploaded file name in view php and set in jquery function.here is code uploaded file.
// controller file this file only when i click upload calling
// controller file
function uploadfileview(){
$targeturl = getcwd()."/uploads/";
if($_SERVER['REQUEST_METHOD'] == "POST"){
$checkexisting = getcwd()."/uploads/".$_FILES['userfile']['name'][0];
$random_number = rand(0,1000000);
//checking the file is existing or not
if(file_exists($checkexisting)) {
if(move_uploaded_file($_FILES['userfile']['tmp_name'][0], $targeturl.$random_number.'-'.$_FILES['userfile']['name'][0])){
echo json_encode(array(
'files' => $random_number.'-'.$_FILES['userfile']['name'][0],
'post' => $_POST,
'fileurl' => getcwd()."/uploads/".$random_number.'-'.$_FILES['userfile']['name'][0]
));
$bb = $random_number.'-'.$_FILES['userfile']['name'][0];
}
}else{
if(move_uploaded_file($_FILES['userfile']['tmp_name'][0], $targeturl.$random_number.'-'.$_FILES['userfile']['name'][0])){
echo json_encode(array(
'files' => $random_number.'-'.$_FILES['userfile']['name'][0],
'post' => $_POST,
'fileurl' => getcwd()."/uploads/".$random_number.'-'.$_FILES['userfile']['name'][0]
));
}
$data['testing'] = $random_number.'-'.$_FILES['userfile']['name'][0];
return $this->$data('reimbursement');
}
// exit;
}
}
Here is the ajax upload form.function.
// for uploaded the file name
jQuery(function(){
var button = $('#uploader-button'), interval;
new AjaxUpload( button, {
action: baseUrl + "expensereimbursement/uploadfileview",
name: 'userfile[]',
multiple: true,
onSubmit : function(file , ext){
// Allow only images. You should add security check on the server-side.
if (ext && /^(jpg|png|jpeg|pdf)$/.test(ext)){
} else {
// extension is not allowed
$('#bq-reimbursement-form .error-ajax').text('Error: Invalid File Format').css('color','red').show().fadeOut(5000);
// cancel upload
return false;
}
// change button text, when user selects file
button.text('Uploading');
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function(){
var text = button.text();
if (text.length < 13){
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response){
button.text('Upload');
window.clearInterval(interval);
// enable upload button
this.enable();
var obj = $.parseJSON(response);
if(obj.error){
$('#bq-reimbursement-form .error-ajax').text('Error: File Already Exist!').css('color','red').show().fadeOut(5000);
}else {
var url = "https://docs.google.com/viewer?url=" + obj.fileurl;
var html = '<li><input type="text" name="imageName[]" value="'+file +'" class="display-type" ><a class="filenames" target="_blank" href="'+url+'">'+file +'</a><span class="close-button display-type">x</span></li>';
$('#upload-file-bq .files').append(html);
}
}
});
});
var html = '<li><input type="text" name="imageName[]" value="'+file +'" class="display-type" ><a class="filenames" target="_blank" href="'+url+'">'+file +'</a><span class="close-button display-type">x</span></li>';
// file = my uploaded file name to be return from controller.
Here file only i want to return the uploaded file name can any one help me please.is this possible get the value in jquery.
CodeIgniter comes with a class for uploading files. You should use it. From looking at the CodeIgniter documentation for the Upload Class. You can do this after you've uploaded your file.
$aUploadData = $this->upload->data()
$aUploadData will then contain an array of data about the file you uploaded. To return the name of the file you uploaded you would do something like this
$aUploadData = $this->upload->data()
return $aUploadData['file_name']

Problems to get jquery to work in json rendered html format

I run a "strip out" version of FB bigPipe and it's working perfect, except the jquery. When I parse the jquery in json format and append to a div tag, the jquery stop working.
You can see the "bigPipe" jquery code I use here
The code to get this working is pretty simple. In PHP:
$data = array(
'id' => {div tag ID},
'content' => {html content},
'title' => {document title},
'css' => {...},
'js' => {...}
);
$output = '<script>Test.render(' . json_encode($data) . ');</script>';
I think the problem is that I have to add window.addEventListener not to the window itself, but to the div tag I append the content.
And here I'm stuck. How do I do this? How do I get this jquery to work in this appended html?
Here is a example on how it should work:
If you try to run this code from a php file problems occur.Do this:
Put the js code from jsFiddle in a js file and include normaly in the .php file. Make a div tag in the php file and call it "not_working"- Save
Make a empty .html document and add a div tag like <div
id="test">Click me</div> and save.
Make a new js file and name it test.js.
Put in this code:
$(function() {
$("body").on("click","#test",function(){
alert("You clicked me!!");
});
});
Save.
In the PHP file, add this: $data = array(
'id' => "not_working",
'content' => {LINK and NAME to the HTML file you created!!},
'title' => "Test",
'css' => "",
'js' => {LINK and NAME to the JS file you created!!},
);
Run the .php file, click on the Click me!.
Problem solved. It was a error in the way the js files was inserted into the body element. After fixing that code. I solved it, and now everything work perfect.
If someone try to use this code, here is the changes:
function _addJsFile(filename) {
var blody = document.getElementsByTagName("body")[0],
script = document.createElement('script'),
done = false;
script.src = filename;
script.type='text/javascript';
script.onload = function() {
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
done = true;
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if (blody && script.parentNode) {
blody.removeChild(script);
}
}
};
blody.appendChild(script);
}

Categories