DropZone JS change default preview image after success - dropzone

So I am having a problem with changing the default image that is displayed after a successful document upload.
I have the following for my DropZone definition;
$(document).ready(function () {
$(".dropzone").dropzone({
renameFilename: function (filename) {
return 'ps' + $('#txtID').val() + '_' + filename;
},
success: function (file, response) {
var ext = getFileExt(file.name);
var newImagePath = file.name;
/* Check for extension */
if (ext != 'png' && ext != 'jpg' && ext != 'jpeg' && ext != 'gif') {
if (ext == 'pdf') {
newImagePath = "/images/icon_pdf128.png";
}else{
newImagePath = "/images/icon_genericfile128.png";
}
}
this.createThumbnailFromUrl(file, newImagePath);
},
url: 'aPageHere',
method: 'post',
dictDefaultMessage: 'Drop files here or click to upload<br>(max 5MB)',
thumbnailWidth: 60,
thumbnailHeight: 60,
maxFilesize: 5,
previewsContainer: ".dropzone-previews",
previewTemplate: document.querySelector('#previews').innerHTML
});
});
The area I am having problems with is the Success function where if it is an image, then fine, DropZone shows a preview of the image, but I am trying to change the image to a PDF pic or a generic picture if required
Any suggestions would be welcome
Thanks
Matt

I assuming the image will be placed on the preview.
You can do a query Selector on your preview as below:
success: function (file, response) {
//Select the preview element
var previewImg = file.previewElement.querySelector('img');
var ext = getFileExt(file.name);
var newImagePath = file.name;
/* Check for extension */
if (ext != 'png' && ext != 'jpg' && ext != 'jpeg' && ext != 'gif') {
if (ext == 'pdf') {
newImagePath = "/images/icon_pdf128.png";
}else{
newImagePath = "/images/icon_genericfile128.png";
}
previewImg.src = newImagePath;
}
}

Related

How to wait until in node js

I want to see if the file is downloaded in the download folder? After downloading the file has to be saved in another folder.
let files = fs.readdirSync('C:\\Users\\xyz\\Downloads')
let tmpfiles+= files.map(file =>file.split('.').pop()=='tmp'? 1:0)
if(tmpfiles<=0){await readSave()}
async function readSave() {
files = fs.readdirSync('C:\\Users\\xyz\\Downloads')
files.forEach(file => {
if (file.includes('abc') && file.includes('EGF') && file.split('.').pop() == 'json')) {
let flpath = 'C:\\Users\\xyz\\Downloads\\' + file
let filedestPath = path.join(dataDir, folderPath, `//${file}`)
let fldata = fs.readFileSync(flpath, 'utf-8')
fs.writeFile(filedestPath, JSON.stringify(fldata), () => removefile(flpath))
}
})
}
function removefile(flpath) {
fs.unlink(flpath, (err) => {
if (err) throw err
})
}

miband7 diy bin: AOD can not change

Because I add a custom AOD clock in the watch file (the code is copied from another open source author, which is an effective code).
But the AOD interface seems to be locked in the original AOD. Did I miss some important settings?
When I set on the normal dial interface, the clock can be displayed in the normal interface, but the AOD clock has not changed. At present, the AOD interface seems to be locked and cannot be modified. However, the official ZEPP development file indicates that AOD display can be set.
https://docs.zepp.com/docs/watchface/api/hmSetting/getScreenType/?_highlight=aod#Screentype-number
Can anyone help me change the AOD clock? Did I miss some important settings? Thank you.
Figure 1: AOD interface, clock is not the style I want to change, it seems to be locked in the official AOD style.
enter image description here
Figure 2: Normal interface. The lowest dotted clock at the bottom is the style I want to change and successfully displayed. But he can only display in the normal interface that the AOD interface has not taken effect.
enter image description here
// aod 显示越少越省电
WatchFace.createWidget(hmUI.widget.IMG_TIME, {
hour_zero: 1,
hour_startX: aodhour_X,
hour_startY: aodhour_Y,
hour_array: aodt_array,
hour_space: 15,
hour_align: hmUI.align.LEFT,
minute_zero: 1,
minute_startX: aodminute_X,
minute_startY: aodminute_Y,
minute_array: aodt_array,
minute_space: 15,
minute_align: hmUI.align.LEFT,
show_level: hmUI.show_level.ONLY_NORMAL | hmUI.show_level.ONAL_AOD,
})
app.js
try {
(() => {
var e = __$$hmAppManager$$__.currentApp;
function t() {
return e.app;
}
const n = {};
function o() {
if ("undefined" != typeof self) return self;
if ("undefined" != typeof window) return window;
if ("undefined" != typeof global) return global;
if ("undefined" != typeof globalThis) return globalThis;
throw new Error("unable to locate global object");
}
t()
? DeviceRuntimeCore.HmUtils.gettextFactory(
n,
t().__globals__.lang,
"en-US"
)
: console.log(n);
let r = o();
r.Logger ||
("undefined" != typeof DeviceRuntimeCore &&
(r.Logger = DeviceRuntimeCore.HmLogger));
let i = o();
i.Buffer ||
("undefined" != typeof Buffer
? (i.Buffer = Buffer)
: (i.Buffer = DeviceRuntimeCore.Buffer));
let u = o();
"undefined" == typeof setTimeout &&
"undefined" != typeof timer &&
((u.clearTimeout = function (e) {
e && timer.stopTimer(e);
}),
(u.setTimeout = function (e, t) {
const n = timer.createTimer(
t || 1,
Number.MAX_SAFE_INTEGER,
function () {
u.clearTimeout(n), e && e();
},
{}
);
return n;
}),
(u.clearImmediate = function (e) {
e && timer.stopTimer(e);
}),
(u.setImmediate = function (e) {
const t = timer.createTimer(
1,
Number.MAX_SAFE_INTEGER,
function () {
u.clearImmediate(t), e && e();
},
{}
);
return t;
}),
(u.clearInterval = function (e) {
e && timer.stopTimer(e);
}),
(u.setInterval = function (e, t) {
return timer.createTimer(
1,
t,
function () {
e && e();
},
{}
);
})),
(e.app = DeviceRuntimeCore.App({
globalData: {},
onCreate(e) { },
onShow(e){},
onHide(e){},
onDestroy(e) { },
onError(e) { },
onPageNotFound(e) { },
onUnhandledRejection(e) { }
})),
(t().__globals__ = {
lang: new DeviceRuntimeCore.HmUtils.Lang(
DeviceRuntimeCore.HmUtils.getLanguage()
),
px: DeviceRuntimeCore.HmUtils.getPx(480)
}),
(t().__globals__.gettext = t()
? DeviceRuntimeCore.HmUtils.gettextFactory(
n,
t().__globals__.lang,
"en-US"
)
: console.log(n));
})();
} catch (e) {
console.log(e);
}

failed to send array in url in workligh application using jquerymobile

I am building a hybrid application in IBM worklight using jquerymobile.
I want to send the json array returned by server php to another page in the url. The codes are shown below:
searchPools.js file
(file from which the another page is called)
$(document).undelegate('#srhPool', 'click').delegate('#srhPool', 'click', function() {
var source = $("#csource1").val();
var destination = $("#cdest1").val();
var poolDate = $("#pooldate1").val();
if(source == null || source == "")
$("#csource1").parent().css('border','2px solid red');
if(destination == null || destination == "")
$("#cdest1").parent().css('border','2px solid red');
if(poolDate == null || poolDate == "")
$("#pooldate1").parent().css('border','2px solid red');
if(source == null || source == "" || destination == null || destination == "" || poolDate == null || poolDate == "" || validateRadio == false){
alert("Oops! Your Pooling Info is Incomplete.");
}
else{
savePool(userId, source, destination, poolDate, preferVehicle);
}
});
//save pool info
function savePool(userId, source, destination, poolDate, preferVehicle){
$.mobile.utils.showWaitBox("a", "Wait! Searching Poolers...");
var invocationData9 = {
adapter : 'registerUser',
procedure : 'searchPoolData',
parameters : [userId, source, destination, poolDate, preferVehicle]
};
WL.Client.invokeProcedure(invocationData9, {
onSuccess : poolSuccess,
onFailure : poolFailure,
});
}
function poolSuccess(result){
$.mobile.utils.hideWaitBox();
var invocationResult = result.invocationResult;
var array1 = invocationResult.pools;
var dataurl2 = '?array='+array1;
$.mobile.changePage('../../pages/passenger/poolResults.html'+dataurl2, {transition: "slide"});
}
function poolFailure(result){
$.mobile.utils.hideWaitBox();
WL.Logger.error('Search Unsuccessful');
}
poolResults.js(the file where the array is accessed)
$(document).on( 'pagebeforeshow', '#poolResults', function(event){
var params = new Array();
function getParams(){
var idx = document.URL.indexOf('?');
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
getArray = unescape(params["array"]);
alert(getArray);
});
Its not working. What I want to do is that I clicked a button in a page, then some results are retreived through http adapters. In the searchPools.js file, the values are successfully obtained in the poolSuccess function. Now, these values are to be displayed on the other page which is showed using $.mobile.changePage. I want to know the way I am using is right, or some other way is available for achieving this.
Send the array like this
$.mobile.changePage('page2.html', { dataUrl : "page2.html?parameter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });
and retrive them like
$("#index").live('pagebeforeshow', function (event, data) {
var parameters = $(this).data("url").split("?")[1];;
parameter = parameters.replace("parameter=","");
alert(parameter);
});
For More Info See The Link
For your understanding Pass it as
$.mobile.changePage("newPage.html", {data:{ param1 : YOUR JSON } });
And retrive it as
<script type="text/javascript">
$("#newPageId").on("pageshow", onPageShow);
function onPageShow(e,data)
{
var url = $.url(document.location);
var param1 = url.param("param1");
}
</script>

Google Gears upload: strange error

I've got this very strange error and I don't know how to deal with it.
My setup is a page in which I can select one image file, (gears beta.desktop) and then it should upload. But it doesn't upload, and gives a very strange error which I can't get away. below is my code:
var filesToUpload = null;
function progressEvent(event) {
var bar = $("#progressBar");
var percentage = Math.round((event.loaded / event.total) * 100);
bar.width(percentage + '%');
}
function uploadState() {
if(request.readyState == 4) {
if(request.status != 200) {
alert('ERROR');
} else {
alert('DONE');
}
}
}
function handleFiles(files) {
if(files.length) {
$('#loader').slideDown(500);
var curFile = files[0];
request.open('POST', 'upload.php');
request.setRequestHeader("Content-Disposition", "attachment; filename=\"" + curFile.name + "\"");
request.onreadystatechange = uploadState;
request.upload.onprogress = progressEvent;
request.send(curFile.blob);
}
}
init = function() {
if(!window.google || !google.gears) {
$('body').css('background', 'white');
$('#gearsOn').hide();
$('#gearsOff').show();
return;
}
// verberg 'geen gears' bericht
$('#gearsOff').hide();
// init upload zooi (gears)
desktop = google.gears.factory.create('beta.desktop');
request = google.gears.factory.create('beta.httprequest');
// on click funct
$('#titel').click(function() {
var newtitle = prompt("Voer een titel in voor het album.");
if(newtitle != '' && newtitle != null) {
$(this).text(newtitle);
}
});
$('.addPictures').click(function() {
filesToUpload = null;
var options = { singleFile: true, filter: [ 'image/jpeg', 'image/png'] };
desktop.openFiles(handleFiles, options);
});
};
$(document).ready(init);
It gives the following error:
[Exception... "Component returned failure code: 0x80004001 (NS_ERROR_NOT_IMPLEMENTED) [nsILoadGroup.groupObserver]" nsresult: "0x80004001 (NS_ERROR_NOT_IMPLEMENTED)" location: "JS frame :: file:///Users/Fabian/Library/Application%20Support/Firefox/Profiles/oo132cjy.default/extensions/%7Be3f6c2cc-d8db-498c-af6c-499fb211db97%7D/components/componentCollectorService.js :: anonymous :: line 1155" data: no]
[Break on this error] obj = getIface(request.loadGroup.groupObserver);
The thing is visible at this location: Dynamics Photo
Thanks in advance!!
I get this error when I'm using page speed - extension to firebug. If you use the same try to deactivate this extension.
disabling page speed did not helped... so uninstalled the extension.. and it works

Timeout XMLHttpRequest

How can I add a timeout to the following script? I want it to display text as "Timed Out".
var bustcachevar = 1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
var bustcacheparameter = ""
function ajaxpage(url, containerid) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else
return false
document.getElementById(containerid).innerHTML = '<img src="load.gif" border="0"><br><br><strong>Generating Link...</strong>'
page_request.onreadystatechange = function () {
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter = (url.indexOf("?") != -1) ? "&" + new Date().getTime() : "?" + new Date().getTime()
page_request.open('GET', url + bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = page_request.responseText
else if (page_request.readyState == 4 && (page_request.status == 404 || window.location.href.indexOf("http") == -1))
document.getElementById(containerid).innerHTML = '<strong>Unable to load link</strong><br>Please try again in a few moments'
}
using the timeout properties of XMLHttpRequest object for example.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert("ready state = 4");
}
};
xhr.open("POST", "http://www.service.org/myService.svc/Method", true);
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.timeout = 4000; // Set timeout to 4 seconds (4000 milliseconds)
xhr.ontimeout = function () { alert("Timed out!!!"); }
xhr.send(json);
the above code works for me!
Cheers

Resources