I need to upload multiple files from jsp. I am using $ajaxFileUPload.js to take the file to server side. I am doing my file size validation in server side for each file. I need a message on validating the file, where i face a problem. I am not able to show that message. Could someone help me in this please?
I have not used the plugin but what I have done previously in similar situation is send different markers back to the client side like for an upload the exceeds the file limit size, you can start the response back with something like 'ERROR:' and then look for this marker in the function getting the response back and then branch to a different logic. You obviously have to parse the response and look for the marker.
Looking quickly at the plugin in Github, it looks like the usage is
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
So what I think you can do is in the onComplete function something like
if (response.search("ERROR:") != -1){
//error condition
//add your msg for the front end here
} else {
//non error condition, continue with your regular flow
}
Does this make sense and relate to what you are trying to do?
Related
I am using the wicket framework.
I have a requirement to send to the client browser several individual files (a zip file is not relevant).
I have added to my page an AJAXDownload class that extends AbstractAjaxBehavior - a solution for sending files to the client like this:
download = new AJAXDownload(){
#Override
protected IResourceStream getResourceStream(){
return new FileResourceStream(file){
#Override
public void close() throws IOException {
super.close();
file.delete();
}
};
}};
add(download);
At some other point in my code I am trying to initiate the download of several files to the client using an ajax request whilst looping through an arraylist of files and then each time triggering the AJAXDownload:
ArrayList<File> labelList = printLabels();
for(int i=0; i<labelList.size(); i++){
file = labelList.get(i);
//initiate the download
download.initiate(target);
}
However, it is only sending just one of these files to the client. I have checked and the files have definitely been created on the server side. But only one is of them is being sent to the client.
Can anyone give me an idea what I am doing wrong?
Thanks
You are doing everything correct!
I don't know how to solve your problem but I'll try to explain what happens so someone else could help:
The Ajax response has several entries like:
<evaluate>document.location=/some/path/to/a/file</evaluate>
wicket-ajax.js just loops over the evaluations and executes them. If there is one entry then everything is OK - you have the file downloaded. But if there are more then the browser receives several requests for changing its location in very short time. Apparently it drops all but one of them.
An obvious solution would be to use callbacks/promises - when a download finishes then trigger the next one. The problem is that there is no way how to receive a notification from the browser that such download finished. Or at least I don't know about it.
One can roll a solution based on timeouts (i.e. setTimeout) but it would be error prone.
I hope this information is sufficient for someone else to give you the solution!
I have a portlet. When the portlet loads, then before the first view is rendered, in some cases there is a need to call a repository which changes data in the database. I wouldn't go into more detail about why this is necessary and answers about this being a design flaw are not helpful. I am aware that it is a design flaw but I would still like to find out an alternative solution to the following problem:
The problem with this set-up is, that browsers send preloading requests. For example the URL of the page where the portlet resides is /test-portlet. Now when you type it in your address-bar then if you have it in your browser history, then the browser sends a GET request to the page already when it suggests it to you. If you press enter before the first GET request is resolved, then the browser sends a new GET request. This means that the portlet receives 2 separate requests which it starts to process parallelly. The first database procedure might work correctly but considering the nature of the database procedure, the second call usually gives an exception.
What would be a nice clean way to deal with the aforementioned problem from the Java application?
Sidenote: I am using Spring MVC.
A simple example of a possible controller:
#RequestMapping
public String index( Model model, RenderRequest request ){
String username = dummyRepository.changeSomeData(request.getAttribute("userId"));
model.add("userName", username);
return "view";
}
I would be interested in a solution to block the first execution altogether. For example somekind of a redirect to POST from controller which the browser wouldn't trigger. Not sure if it is achievable though.
Using locks I think you could solve it, making the secound request wait for the first to finish and then processing it. I don't have experience with locks in java but i found another stack exchange post about file locks in jave:
How can I lock a file using java (if possible)
Please refer to this answer, it might help you to detect and ignore some preloading requests. However you should also make sure the 'worst case' works, perhaps using the locking as suggested by #jpeg, but it could be as easy as using a synchronize block somewhere.
Since I don't see that chrome adds some specific header (or anyhow notifies the server about prerendering state) it is probably not possible to detect it on the server side... at least not directly. You can however simulate the detection on client side and later combine it with server call.
Notice that you can detect prerendering on the client side:
if (document.webkitVisibilityState == 'prerender' || document.visibilityState == 'prerender' || document.visibilityState[0] == 'prerender') {
// prerendering takes place
}
Now, you can break preloading on client side by showing alert box in case browser is in preloading state (or you can probably do the same with just some error in javascript, instead of using alert()):
if (document.webkitVisibilityState == 'prerender' || document.visibilityState == 'prerender' || document.visibilityState[0] == 'prerender') {
alert('this is alert during prerendering..')
}
Now when chrome prerenders the page it will fail because the javascript alert will prevent the browser to continue executing javascript.
If you type in chrome: chrome://net-internals/#prerender you can track when and for which pages chrome executes prerendering. In case of above example (with alert box during prerendering) you can see there:
Link Rel Prerender (cross
domain) http://some.url.which.is.preloaded Javascript
Alert 2015-06-07 19:26:18.758
The final state - Javascript Alret proves that chrome failed to preload the page (I have tested this).
Now how can this solve your issue? Well, you can combine this with asynchronous call (AJAX) and load some content (from another url) depending on wheater the page is actually prerendering or not.
Consider following code (which might be rendered by your portlet under url /test-portlet):
<html>
<body>
<div id="content"></div>
<script>
if (document.webkitVisibilityState == 'prerender' || document.visibilityState == 'prerender' || document.visibilityState[0] == 'prerender') {
// when chrome uses prerendering we block the request with alert
alert('this is alert during prerendering..');
} else {
// in case no prerendering takes place we load the actual content asynchronously
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// when the content is loaded we place the html inside "content" div
document.getElementById('content').innerHTML = xhr.responseText;
}
}
xhr.open('GET', '/hidden-portlet', true); // we call the actual portlet
xhr.send(null);
}
</script>
</body>
</html>
As you see the /hidden-portlet is only loaded in case browser is loading the page normally (without preloading). The server side handler under url /hidden-portlet (which can be another portlet/servlet) contains actual code which should not be executed during prerendering. So it is the /hidden-portlet which executes
dummyRepository.changeSomeData(request.getAttribute("userId"));
This portlet can also return normal view (rendered html) which will be asynchronously placed on the page under url /test-portlet thanks to the trick on /test-portlet: document.getElementById('content').innerHTML = xhr.responseText;.
So to sumarize the portlet under address /test-portlet only returns html with a javascript code which triggers actual portlet.
If you have many fragile portlets, you can go with this even further, so you can parametrize you /test-portlet with request parameter like /test-portlet?actualUrl=hidden-portlet so that address of the actual portlet is taken from url (which can be read as request parameter on server side). Server will in this case dynamically render the url which should be loaded:
So instead of hardcoded:
xhr.open('GET', '/hidden-portlet', true);
you will have
xhr.open('GET', '/THIS_IS_DYNAMICALLY_REPLACED_EITHER_ON_SERVER_OR_CLIENT_SIDE_WITH_THE_ADDRES_FROM_URL', true);
(When I say "App" I am only talking about Android, I'm not gonna even try to deal with Apple)
So I have a website that I'd like to develop an Android app for. All I need it to do is show the website(it'll change some styling if being accessed from the app), which I can do just fine.
I use Intel XDK, which works great. But the notification options it offers seems to be just mass-notification stuff, not individualized.
All I want to do is be able to tell users when they get a notification from my website(like a message from another user).
I've looked all over the place for hours and hours and can't find anything useful. There are a ton of extremely complicated Java codes and tutorials, but I don't even know Java. I'm solely a web developer and all I want is an app that makes it easier for users to check the website.
I'm hoping there is some Java file out there that I can send data to somehow that will allow me to create and delete push notifications on Android systems. Maybe a HTML5 library or JS function, I dunno.
I simply can't seem to implement it myself, and I'm definitely not going to learn an entire dying language just for one basic thing that should be simple to do. Anything you guys can provide would be greatly appreciated. Optimally I would like to get a Java file I can download and put into my app that gives a notification, then I can edit it to say what I need it to or whatever(I also would really like a way to make the notification go away[in case the user sees it on another device before seeing it on the phone] ). I would also need to know how to call onto this Java file, make it check for notifications on the server or whatever.
I know this is all very nooby stuff, but I run an independent website and simply don't have the time to learn all this stuff when my needs are so basic. Thanks in advance.
You can use appMobi for push messaging, see documentation at http://docs.appmobi.com/index.php/push-messages/pushjsapi/. You can setup your appMobi account in the Services tab of the Intel XDK.
//Check if user is registered
var onDeviceReady=function() {
//See if the push user exists already
//You can send any unique user id and password.
AppMobi.notification.checkPushUser(AppMobi.device.uuid, AppMobi.device.uuid);
};
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
//if user is not registered, register them
var isUserAdded = false;
var notificationsRegistered=function(event) {
if(event.success === false) {
if (!isUserAdded) {
isUserAdded= true;
AppMobi.notification.addPushUser(AppMobi.device.uuid,
AppMobi.device.uuid,
'no#email.com');
return;
}
AppMobi.notification.alert("Notifications Failed: " + event.message,
"My Message","OK");
return;
}
var msg = event.message || 'success';
AppMobi.notification.alert("Notifications Enabled: " + msg,
"My Message","OK");
};
document.addEventListener("appMobi.notification.push.enable",
notificationsRegistered,false);
//when push message event is found get notification
var receivedPush = function(){
var myNotifications=AppMobi.notification.getNotificationList();
//It may contain more than one message, so iterate over them
var len=myNotifications.length;
if(len > 0) {
for(i=0; i < len; i++) {
msgObj=AppMobi.notification.getNotificationData(myNotifications[i]);
try{
if(typeof msgObj == "object" && msgObj.id == myNotifications[i]){
AppMobi.notification.alert(msgObj.msg + "\n" + msgObj.data
+ "\n" + msgObj.userkey,"pushMobi Message","OK");
//Always delete messages after they are shown
AppMobi.notification.deletePushNotifications(msgObj.id);
return;
}
AppMobi.notification.alert("Invalid Message Object: " + i,
"My Message","OK");
}catch(e){
AppMobi.notification.alert("Caught Exception For: " + msgObj.id,
"My Message","OK");
AppMobi.notification.deletePushNotifications(msgObj.id);
}
}
}
};
document.addEventListener("appMobi.notification.push.receive", receivedPush, false);
//send a push notification from your website
AppMobi.notification.sendPushNotification(myAppMobiUserID,"new website blog posted!",{});
document.addEventListener("appMobi.notification.push.send",updateNotificationEvent,false);
var updateNotificationEvent=function(event)
{
if(event.success==false)
{
alert("error: " + event.message)
}
else
{
alert("success");
}
}
You can also use Parse.com APIs but I don't believe the subscribe to channel JavaScript API is fully flushed out last I checked, see https://www.parse.com/docs/push_guide#top/JavaScript.
Parse.initialize("YOUR KEY", "HERE");
// Save the current Installation to Parse.
ParseInstallation.getCurrentInstallation().saveInBackground();
You can then send push notifications through the Web Console, or on your website using:
//The following code will push the alert to the "Winterhawks" and "Oil Kings" channels.
Parse.Push.send({
channels: [ "Winterhawks", "Oil Kings" ],
data: {
alert: "The Winterhawks won against the Oil Kings!"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
Subscribe to channels is not yet implemented for JavaScript as far as I know so you'll have to use REST or native APIs.
I have a web application which serves as the Admin Panel. It has a live chat option which connects with writers(employees) on the other end. The web application uses the following PHP code to check for online writers.
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while ($q<5){
sleep(3);
$wresult = $db->query("SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if ($wresult->num_rows){ break; }
++$q;
}
if ($wresult->num_rows){
while ($row = $wresult->fetch_object()){ $writers[] = $row; }
$wresult->free();
}
echo json_encode(
array(
"writers" => $writers,
"now" => time()
)
);
On the application the following javascript code handles the PHP response and calls ajax again to complete the loop.
function UpdateCHAT(){
$.ajax({
type: "POST",
url: "liveserver.php",
data: {update:"1",timestamp:lastime},
success:
function(data1){
if (data1 == null){
$(".onlinechat i").removeClass("icon-white");
}else{
lastime = user_signin = Number(data1.now);
if (!data1.writers.length){
$(".onlinechat i").removeClass("icon-white");
}else{
$(".onlinechat i").removeClass("icon-white");
$.each(data1.writers,function(j) {
$("#writer_"+data1.writers[j].writer_alias).find("i").addClass("icon-white");
});
}
}
},
dataType: "json",
timeout: 60000,
complete:
function(){
UpdateCHAT();
}
}
);
}
Everything is working just fine except the fact that I cannot think of a way to know for offline writers since the PHP code is designed to check for the online writers, but this means if a writer is online once, he will remain online (on the application) until the PHP code dies and return empty writers.
Hope I am able to explain my point. This question is more to do with idea rather than piece of code. Any input is appreciated.
Thanks.
Make the PHP code always return after some time (like 2 minutes) with an empty result set (ie. no new chat lines).
JS will then do a new request immediately. If it doesn't, well, then the user is offline. Keep a last_request timestamp, if it's older than 2+e minutes the user is offline.
You could try to detect when the connection closes in PHP. Set ignore_user_abort(true) so you are in control of when your script dies. Then use connection_aborted() to check if the client closed. If he did you know he left.
A potential problem occurs if the user has two windows open: a close on one doesn't mean he left, but this may turn out to be acceptable; the user will blip for just a while.
Another solution is to use a separate ping request that just tells you "yep, I'm still here". If you haven't gotten one of those in a while the user is probably offline.
As I talk about befor I'm using to jQuery to refresh / update a webcam image.
This works just fine if you wanna update the image every 5th or 10sec.
But when your gonna do a stream with 10-15fps it gets into problems with most browsers
it seems. The problem seem to be that it sends a request befor the first one was done.
Is there a way to wait for the first request to be done befor sending a new update request for the webcam image? Because to me it seems to stack up requests if there is alittle delay on the server with the image.
Sorry if I did explain it alittle bad but... I'm norwegian and blode. Not the best combination. :)
Webcam Image is a single url
ex. http://www.ohoynothere.com/image.jpg
Old code I use.
$(document).ready(function() {
setInterval('updateCamera()',3000);
});
function updateCamera() {
$('.online2').each(function() {
var url = $(this).attr('src').split('&')[0];
$(this).attr('src', url + '&rand=' + new Date().getTime());
})
}
Definitely!
It sounds like your best bet would be to use the jQuery.ajax() method ( http://api.jquery.com/jQuery.ajax/ ) or .get() method to chain your requests. Basically, you want a JavaScript function that does a request for the image using the .ajax() call. In the response handler, simply call the function again:
function getMyImage() {
jQuery.get(image_url, function(response) {
jQuery('#img-name').attr('src', response);
getMyImage();
});
}
Whenever getMyImage successfully returns the image's src value from the webcam, it will immediately go out and try to retrieve a new image, but not before the previous one is loaded.
If I haven't understood what you're trying to do, please let me know. It would be helpful to know more about how the webcam image is retrieved (i.e. is it the same image src returned every time, etc.).