How to process backend coldfusion processing script response - jquery-ui

I have implemented plupload using a ColdFusion backend script (available at https://gist.github.com/1116037).
The url attribute in the uploading page is url : '../upload.cfc?method=upload',
This simply calls a function within the cfc script. It works fine. This script also creates a variable called 'response' to hold information uploaded files.
The problem I am having is accessing the information held in the 'response' variable.
I would like to display that information in a table after the all the files have been uploaded to the server.
I am using the queue_widget for my needs’ think that an event (onComplete) needs to be triggered to call a function to process the information in variable, but I don't know how to do this.
I need to access the information held in the 'response' variable, preferably in ColdFusion code. Has anyone managed to get plupload working with ColdFusion yet?
Any help, guidance or coding would be appreciated.
Here is the full code I have used:
This is the main page - queue_widget.cfm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Plupload - Queue widget example</title>
<link rel="stylesheet" href="../../js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../../js/plupload.js"></script>
<script type="text/javascript" src="../../js/plupload.flash.js"></script>
<script type="text/javascript" src="../../js/jquery.plupload.queue/jquery.plupload.queue.js"></script>
</head>
<body>
<h1>Queue widget example</h1>
<p>Shows the jQuery Plupload Queue widget and under different runtimes.</p>
<div style="float: left; margin-right: 20px">
<h3>Flash runtime</h3>
<div id="flash_uploader" style="width: 700px;">Your browser does not have Flash installed!</div>
</div>
<br style="clear: both" />
<cfoutput><cfset mnum=6></cfoutput>
<script type="text/javascript">
$(function() {
// Setup flash version
$("#flash_uploader").pluploadQueue({
// General settings
runtimes : 'flash',
url : '../upload.cfc?method=upload',
max_file_size : '1mb',
max_file_count: <cfoutput>#mnum#</cfoutput>, // You can limit the num of files that can be uploaded by manipulating the mnum variable above
unique_names : false,
multiple_queues : true,
multi_selection: true,
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
],
init : {
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
if (up.files.length > <cfoutput>#mnum#</cfoutput>) {
up.removeFile(file);
}
});
if (up.files.length >= <cfoutput>#mnum#</cfoutput>) {
$('#pickfiles').hide('slow');
}
},
FilesRemoved: function(up, files) {
if (up.files.length < 1) {
$('#pickfiles').fadeIn('slow');
}
}
},
resize : {width : 300, height : 10000, quality : 90}, // forces images to be resized to a width of 300px if wider than 300px
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, response){
function IsJson(response) {
alert('Response from server: ' + response.file); // for testing only
counter++
var newRow = '<tr><td><input type="hidden" name="file_'+counter+'" value="'+response.file+'">'
newRow += 'Label the file: '+response.file+' <input type="text" name="filename_'+counter+'"></td></tr>'
$("#detail").append(newRow)
}});
};
</script>
<div id="results"></div>
<table id="detail">
</table>
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
</body>
</html>
This the backend processing page - upload.cfc
<cfcomponent>
<cffunction name="upload" access="remote" returntype="struct" returnformat="json" output="false">
<cfscript>
var uploadDir = expandPath('/uploads/'); // should be a temp directory that you clear periodically to flush orphaned files
var uploadFile = uploadDir & arguments.NAME;
var response = {'result' = arguments.NAME, 'id' = 0};
var result = {};
</cfscript>
<!--- save file data from multi-part form.FILE --->
<cffile action="upload" result="result" filefield="FILE" destination="#uploadFile#" nameconflict="overwrite"/>
<cfscript>
// Example: you can return uploaded file data to client
response['size'] = result.fileSize;
response['type'] = result.contentType;
response['saved'] = result.fileWasSaved;
return response;
</cfscript>
</cffunction>
</cfcomponent>
You can try the above example here: [url] www.turn2cash.co.uk/plupload/examples/jquery/queue_widget.cfm [/url]
As mentioned above, the script works well with uploading (in this case) upto 6 images as determined by the mnum variable. What I need help with is with how to access the uploaded files (with page refresh) and be able to manipulate them.
I have setup an example (using cffileupload) of what I am after here [url] www turn2cash.co.uk/a/index.cfm [/url]
Although this works fine, it requires a page refresh, which is what I am trying to avoid.
Please provide any help you can.
Added 7 september 2012
I have tried both methods suggested by Miguel but did not achieve any positive outcomes. They actually caused the UI not to sow at all. However I found this and tried it:
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, Response){
alert('Response from server: ' + Response.response);
});
};
</script>
I now get an alert displaying:
Response from server: {"saved":true,"result":"home.png","id":"0","size":"5988","type":"image"}
This at least prooves that the cfc script is working and the 'response' varialable is being returned. I still have no idea how to make use of this information as I have no knowledge of jquery, ajax or javascript. Please help if you can.

The link that I posted before has the example code. Sorry to post this as an answer but since I have no rep I cannot comment.
I think part of your confusion is in the request processing. You have this line of code at the bottom of your example.
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
That will never fire because the coldfusion page is processed before you make the javascript ajax call to the server for the file upload. You will need to handle the response in javascript.
Are you seeing this alert from the attachCallbacks function?
alert('Response from server: ' + response.file); // for testing only

Related

jsPDF - fromHTML does not write at the correct page

I am doing a small project with jsPDF.
I need to write colored text, changing the font size and using bold text. Therefore fromHtml is my choise, because i can easyly do it with css and html.
The problem is that only around the half of the page can be used to write with fromHtml. If it try to write beyond it a new page is created and the text is wirtten there.
Here a small html example with the javascript code, that can be run on it´s own.
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
<script type="text/javascript">
function fromHtmlTest() {
var doc = new jsPDF({
orientation: 'l',
unit: 'px',
format: [30, 30]
});
// doc.setFontSize(1); // the workaround for this problem
var toWrite = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th"];
for (var i = 0; i < toWrite.length; i++) {
doc.fromHTML(
'<div style="font-size:1">' + toWrite[i] + '</div>'
, 1 // x
, i // y
, {
'width': 10,
'elementHandlers': {}
}
)
}
doc.save('Test.pdf');
}
</script>
<body>
<input type="button" value="Start" onclick="fromHtmlTest()" />
</body>
Here an immage of the pdf after running the code:
fromHtml example - code result
"8th" should be directly under "7th" and not at the next page.
If "9th" would be added to the array another page would also be added.
How can i use the whole page with fromHtml?
Edit:
As workaround "doc.setFontSize(1);" does the trick. I have added it to the example code as a comment.

Allow Dropzone js to upload only zip files

In my mvc net core app I need to implement drag&drop files uploader. I found Dropzone js and hoping to use it in my purposes. But can't configure it, I need to allow it upload ony zip files.
My code:
<div class="row">
<div class="col-md-9">
<div id="dropzone">
<form action="/Home/Upload" class="dropzone needsclick dz-clickable" id="uploader">
<div class="dz-message needsclick">
Drop files here or click to upload.<br>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function () {
Dropzone.options.uploader = {
paramName: "file",
maxFilesize: 256,
acceptedFiles: "application/zip,application/octet-stream,application/x-zip-compressed,multipart/x-zip,.zip",
maxFiles: 1
};
});
</script>
Also of course I have controller:
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
var uploads = Path.Combine(_environment.ContentRootPath, "Uploads");
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
return RedirectToAction("Index");
}
But still, application allows to upload any file with any MIME type. Where is a problem?
Also restriction of maxFiles isn't working too - it allows me to upload infinite count of files.
You can use option of dropzone.js name acceptedfile.
Dropzone.options.myAwesomeDropzone = {
....
acceptedFiles: ".zip",
....
};
According to the documentation (https://www.dropzonejs.com/#configuration), you can do it like this:
Dropzone.options.myAwesomeDropzone = {
accept: function(file, done) {
if (file.name.endsWith !== ".zip") {
done("Naha, you don't.");
}
else { done(); }
}
};
A function that gets a file and a done function as parameters. If the
done function is invoked without arguments, the file is "accepted" and
will be processed. If you pass an error message, the file is rejected,
and the error message will be displayed. This function will not be
called if the file is too big or doesn't match the mime types.
Edit:
Here is a fiddle to demonstrate it: http://jsfiddle.net/behyzjng/15/
Set acceptedFiles: 'application/zip' in defaultOptions
Here are the documentation for you to work on Dropzone.js:
Github: https://github.com/dropzone/dropzone
Docs: https://docs.dropzone.dev
check all avaliable options at https://github.com/dropzone/dropzone/blob/main/src/options.js
check the desired extensions allowed and write the MIME type as a value of acceptedFiles at https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
Working solution here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/dropzone#5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone#5/dist/min/dropzone.min.css" type="text/css" />
<title>Document</title>
</head>
<body>
<style>
.my-dropzone {
width: 100%;
height: 100px;
border: 1px dashed;
display: flex;
align-items: center;
justify-content: center;
}
</style>
<div class="my-dropzone">
Drag and drop zip files here, or click here to upload.
</div>
<script>
// Dropzone.js
// Github: https://github.com/dropzone/dropzone
// Docs: https://docs.dropzone.dev
// check all avaliable options at
// https://github.com/dropzone/dropzone/blob/main/src/options.js
const defaultOptions = {
url: "/file/post",
// check the desired extensions allowed and write the MIME type as a value of acceptedFiles at
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
acceptedFiles: 'application/zip'
};
// Dropzone has been added as a global variable.
const dropzone = new Dropzone("div.my-dropzone", defaultOptions);
</script>
</body>
</html>

Office.js function not working in MVC application for Word Online

I have a .NET MVC project for Word online. The add-in starts up successfully but it does not load "Home.js" which calls Office.initialize to insert data into the body of word.
Here is _Layout.cshtml:
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
#Styles.Render("~/bundles/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body ng-app="">
<div class="container">
#RenderBody()
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/Scripts/Office/1/office.js")
#Scripts.Render("~/Scripts/Home.js")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/Scripts/angular.min.js")
</body>
</html>
And Home.js:
(function () {
"use strict";
Office.initialize = function (reason) {
$(document).ready(function () {
if (!Office.context.requirements.isSetSupported('WordApi', '1.1')) {
return;
}
loadSampleData();
});
};
function loadSampleData() {
// Run a batch operation against the Word object model.
Word.run(function (context) {
// Create a proxy object for the document body.
var body = context.document.body;
// Queue a commmand to clear the contents of the body.
body.clear();
// Queue a command to insert text into the end of the Word document body.
body.insertText("This is a sample text inserted in the document",
Word.InsertLocation.end);
// Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
return context.sync();
})
.catch(errorHandler);
}
function errorHandler(error) {
console.log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
console.log("Debug info: " + JSON.stringify(error.debugInfo));
}
}
})();
Thank you.
You're only executing if WordAPI v1.1 is available. This API is only supported in Word 2016 for Windows, Mac and iPad. If you're using Word Online or Word 2013 this code will exit (return) without executing anything.
One other note, you're referencing Office.js and Home.js at the bottom of the <body>. You only have 5 seconds to complete Office.initialize() and placing it at the bottom of the page will require everything load before the browser executes that function. While this is absolutely the proper thing to do for a web site, it will result in time-out errors with Add-ins. These references should always be placed within the <header>.

video.js not working properly with jquery mobile

I am trying to use video.js(gitHub link - https://github.com/videojs/video.js ) plugin in my jquery mobile project to get custom video player, I followed all the documentation from this site (http://videojs.com/), but due to some reasons I am getting following errors -
The element or ID supplied is not valid. (videojs).
this[a] is not a function.
My code -
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="Js/jquery.js"></script>
<script src="Js/jquery.signalR-2.1.2.min.js"></script>
<script src="Js/jquery.mobile-1.4.5.js"></script>
<link href="mcss/jquery.mobile-1.4.5.css" rel="stylesheet" />
<link href="http://vjs.zencdn.net/4.12/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.12/video.js"></script>
<script type="text/javascript">
videojs("Mobile_VIDEO_1").ready(function () {
var vid = this;
vid.on("ended", function () {
alert("is");
$("#videoListXYZ").css("display", "block");
});
});
</script>
</head>
<body>
<div data-role="page" id="p-forget-password">
<div data-role="main" class="ui-content ui-body-cf ui-responsive">
<!-- inserted dyanamically using handlebars template "http://handlebarsjs.com"/ -->
<video id="Mobile_VIDEO_1" class="video-js vjs-default-skin" controls data-id="{{VideoId}}" data-setup='{ "plugins" : { "resolutionSelector" : { "default_res" : "360" } } }' autoplay="autoplay" width="340" height="250">
<source src="{{Path}}" type="video/mp4" data-res="360" />
</video>
</div>
</div>
</body>
Please help me to find out what I am doing wrong.
-I tried using putting videojs(xyx).ready(....) inside document.ready
- I also tried sending my script at the bottom of my page as suggested by (http://help.videojs.com/discussions/problems/985-api-ready-call-fails), but it still not working
After many hit and trial, I realized that my event is firing much before the DOM initialization, so I searched for how to check when the whole page is fully loaded and I come across this document (https://css-tricks.com/snippets/jquery/run-javascript-only-after-entire-page-has-loaded/) from this link I used this
$(window).bind("load", function() {
// code here
});
to check if my page is fully loaded or not . my final solution is mentioned below , if any of you come across a better solution then please share that to help others.
$(window).bind("load", function () {
var videoPath = $('#sv1').attr('src'); //to get the path of video
if (videoPath != "" && videoPath != null) { //checking for non-empty path
console.log(videoPath);
videojs('MY_VIDEO_1', { "plugins": { "resolutionSelector": { "default_res": "360" } } }, function () {
console.log('Good to go!');
this.play();
this.on('ended', function () {
console.log('awww...over so soon?');
$("#videoList").css("display", "block");
});
});
$("#replay").click(function () {
var myPlayer = videojs("MY_VIDEO_1");
myPlayer.play();
});
}
});

getting current URL from popup.hml and send it to external.js

been searching without finding a solution for me,
I need to be able to send and recive current tab URL when the Chrome extension is shown:
this is My popup.html:
<html>
<head>
<style>
div, td, th { color: black; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script>
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
return tab.url;
});
}
</script>
<script src="http://keepyourlinks.com/API/public/chrome.js"></script>
</head>
<body style="width: 650px;height:600px;margin:0px;paddin:0px;width:100%;">
<span class="keeper">keep</span>
</body>
</html>
An then, in my webiste, on a chrome.js file i try:
$("body").ready(function(){
var url = getURL_please();
$(".keeper").click(function(event) {
event.preventDefault();
window.open("http://keepyourlinks.com/API/public/compartir_link.php?url="+url,'about to keep', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=600');
});
});
But URL is allways: Undefined
Any idea what i'm doing wrong?
Thanks a lot!
HI Toni,
Google Chrome Extensions use an Asynchronous API,
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
return tab.url;
});
}
The above will always return null. If you want to make it work correctly.
function getURL_please(){
chrome.tabs.getSelected(null, function(tab) {
var url = tab.url;
// Do what you want here.
});
}
You would need to the windows open after you you fetch the url. One question though, what do you mean "in your website"? You cannot run Chrome Extension JavaScript directly on your website, so I assume via "Content Script" (most likely, just making sure)?
If your using a Content Script, why would you need to use the Extension API? You can just use window.location.href

Resources