How to raise onError from chunking success endpoint in Fine-uploader - fine-uploader

In my application, when the chunking-success-endpoint returns JSON like {"error": "reason..."} (for example the server failed to put the chunks back together), the onError event is not being called.
Just to clarify, the onError event is called if individual chunks fail. It's the final success request that I'm having trouble with.
I'm not sure what I'm missing. Should I be handling this some other way?
My configuration is below. Thanks in advance!
var uploader = $('#fine-uploader').fineUploader({
template: 'qq-template',
debug: true,
callbacks: {
onAllComplete: function(succeeded, failed) {
$('#doclib_tree').jstree(true).refresh()
if (failed.length > 0) {
alert("Error: Some files were not uploaded");
} else {
if (succeeded.length > 0 ) {
alert("Successfully uploaded " + succeeded.length + " file(s)");
}
this.reset();
toggle_upload();
}
},
onError: function(id, name, errorReason, xhrOrXdr) {
alert("Error uploading " + name + ". Reason: " + errorReason)
},
onSubmit: function(id, name) {
var promise = new qq.Promise();
var dest = document.getElementById('dest_label').innerHTML.replace(/ > /g, "/")
$.ajax({
'type': 'POST',
'async': false,
'url': "/documents/exists" ,
'data': {
'parents' : get_path(dest),
'name': name,
},
'success': function(data, textStatus, jqHXR) {
if ( check_session(data) ) {
promise.failure();
} else {
if (confirm("The file '" + dest + "/" + name + "' already exists. Replace?"))
promise.success();
else
promise.failure();
}
},
'error': function(jqHXR, textStatus, errorThrown) {
promise.success();
}
});
return promise;
},
},
chunking: {
enabled: true,
partSize: 20000000, // 20MB
success: {
endpoint: "documents/upload?success=1",
}
},
resume: {
enabled: true,
recordsExpireIn: 1, // 1 day
},
request: {
endpoint: "/documents/upload",
},
autoUpload: true
});

From the documentation under the chunking success section:
For successful responses, you may return an empty body with a status of 200-204. Any other status code is determined to be a failure.
In other words, to indicate failure, you must return a status code that indicates failure. Pick the most appropriate status code given the context of the error. At that point, Fine Uploader should determine that the file has failed in some way, and your onError handler will be called with the error property returned by your server.

Related

How to get(handle) Error (Not Acceptable & Internal Server Error) Exception content in Ajax

I added internal Error (throw exception) in server side. Now I want to handle this error in client side. However , I get error content undefined.
I am using Postman , and see my response is JSON format, it has response parameter like "Message". I tried to parse JSON , and again I got Cannot read property 'Message' of undefined
Ajax function defined like this:
function Ajax(url, method, json, successFunction, errorFunction, skipErrorDlg) {
$.ajax({
url: url,
data: json,
type: method,
contentType: 'application/json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', GlobalAuthToken);
},
processData: false,
dataType: 'json',
success: function (data) {
successFunction(data);
},
error: function(event, jqxhr, settings, thrownError) {
if (errorFunction != null) {
errorFunction();
}
}
});
}
I used this function in my code , error part like this, In this function how can I get exception content?
function(event, jqxhr, settings, thrownError)
{
alert("ERROR HAPPENED");
var responseString = JSON.stringify(event);
alert(responseString.Message);
alert("event" + event.Message);
},
Postman Result:
{
"Message": "Please select corresponding template."}
Expected Result should be : Please select corresponding template.
I solved the problem, if you face this kind problem , trying like this:
function showAjaxError(event, jqxhr, settings, thrownError) {
var msg = "";
if (event.hasOwnProperty('responseJSON')) {
var resp = event['responseJSON'];
msg = (resp && resp.hasOwnProperty('Message')) ? resp.Message : "";
msg = msg + ((resp && resp.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.ExceptionMessage : "");
if (resp && resp.hasOwnProperty('InnerException')) {
msg = msg + ((resp && resp.InnerException.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.InnerException.ExceptionMessage : "");
}
} else {
msg = event.responseText;
}
}

InvalidStateError - Kendo UI Upload

I keep getting this weird bug where when I try to set my Authorization header, I keep getting 'InvalidStateError'. Here is my code:
$("#files").kendoUpload({
async: {
saveUrl: myApiUrl + "/" + id,
autoUpload: true
},
upload: function(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onReady(e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
}
});
}
}
});
It turns out that IE for some reason fires the readystatechange twice for readyState==1. I dont know why but it does. Its the second time that it calls it that make it throw the error. So here is my solution:
After the first time it is called, I just remove the listener.
$("#files").kendoUpload({
async: {
saveUrl: myApiUrl + "/" + id,
autoUpload: true
},
upload: function(e) {
var xhr = e.XMLHttpRequest;
if (xhr) {
xhr.addEventListener("readystatechange", function onReady(e) {
if (xhr.readyState === 1 /* OPENED */) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.removeEventListener("readystatechange", onReady);
}
});
}
}
});

Call an ajax function after every 10 sec, if success stop else proceed till success

I am tring to download a file, via ajax call.
It should process every 20secs.
If file present it will get downloaded and shall stop the futher ajax call, else same ajax should be processed till file is downloaded.
Below is what i have tried
$.ajax({
url: baseUrl + '/ajax/exportStudentInformation',
data: {
'studentId' : studentId
},
type: "post",
success: function(response) {
setTimeout(function () {
timeIntervalDownLoadFile = downloadFile(studentname);
}, 60000);
},
error: function(){
alert('There was error in processing csv file, please try again');
}
});
This is the function that needs to check if the file is present on the cloud and download it.
downloadFile: function(studentname) {
$.ajax({
url: baseUrl + '/ajax/downloadFile',
data: {
'studentname': studentname
},
'type': 'POST',
error: function(jqXHR, status, error) {
alert('There was error in downloading file, please try again!!!');
},
abort: function(jqXHR, status, error) {
},
beforeSend: function() {
var message = "The file is being downloaded, please wait";
$('#alertBar').html("<div class=\"alert alert-info\" >"+message+"<a class=\"close\">×</a></div>")
$("#alertBar").fadeTo(2000, 500).slideUp(500, function(){
$("#alertBar").slideUp(500);
});
},
success: function(response) {
if (response.status) {
window.location.href = "https://urlwhereFileisStoredOnCloud/"+response.filename;
} else {
var message = "File does not exist, please use export to generate file";
$('#alertBar').html("<div class=\"alert alert-danger\" >"+message+"<a class=\"close\">×</a></div>")
$("#alertBar").fadeTo(2000, 500).slideUp(500, function(){
$("#alertBar").slideUp(500);
});
$("html, body").animate({ scrollTop: $('#alertBar').offset().top }, 1000);
}
},
});
},
I have used set interval of jquery to call the second function time after delay. but it does not stops once the file download popup is shown. Any help will be apprciated.

WebKitFormBoundary header on file ulpoad

To avoid sharing a third-service api token, I want to upload my files trough my node server.
To do this, I've my webpage sending my files in ajax to my node server which is sending them to the 3rd party api.
so :
client > ajax > node > api
My file succeed to arrive on the third party service but with WebKitFormBoundary header and footer.
------WebKitFormBoundaryBvPXh46XrNOYDFJn
Content-Disposition: form-data; name="file"; filename="Screen Shot 2014-11-20 at 15.01.45.png"
Content-Type: image/png
<< file bytes >>
------WebKitFormBoundaryBvPXh46XrNOYDFJn--
Ajax code :
$.uploadFiles = function(file){
var data = new FormData();
data.append('file', file, file.name);
console.log(data);
$.ajax({
//url: 'https://slack.com/api/files.upload?token=xoxp-2964595734-2964595740-3128685143-b1796a&channels='+settings.joinedChannel+'&pretty=1',
url: '/app/fileUpload?token='+settings.token+'&channel='+settings.joinedChannel,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
//submitForm(event, data);
console.log(data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
};
Node code
app.post('/app/fileUpload', isAuthorized, function(req, res, next) {
var token = req.param('token');
var channel = req.param('channel');
var req = req;
models.app.find({ where: { token: token, active: true } }).success(function(application) {
slack.uploadFile(application.slack_api_token,channel,req);
return res.status(200).json({ success: true, message: "Uploading" });
});
});
[....]
uploadFile: function uploadFile(applicationToken,channel,file) {
var formData = {
// Pass a simple key-value pair
token: applicationToken,
// Pass a simple key-value pair
channels: channel,
// Pass data via Streams
file: file
};
request.post('https://slack.com/api/files.upload?pretty=1', { formData: formData }, function (error, response, body) {
if (!error && response.statusCode == 200 && typeof body.ok !== "undefined" && body.ok == true) {
console.log("OK");
//console.log(body);
} else {
console.log("Not OK");
//console.log(response);
}
});
},
FIXED : with formidable and this code to manage the file stream :
file: {
value: fs.createReadStream(stream.file.path),
options: {
filename: stream.file.name,
contentType: stream.file.type
}
}

Facebook wall post using ajax post request inconsistent with Chrome and IE

I am using the posted code for posting content to a Facebook wall.
FB.init({ appId: 'my app id', status: true, cookie: true, xfbml: true, oauth: true })
$('#share_button').click(function (e) {
if ($('#textfield').val() != 'Whats Happening' && $('#textfield').val() != '') {
var lin = window.location.href;
FB.login(function (response) {
if (response.authResponse) {
console.log("User is connected to the application.");
var accessToken = response.authResponse.accessToken;
var fbURL = "https://graph.facebook.com/me/feed?access_token=" + accessToken;
$.ajax({
url: fbURL,
data: "message=" + $('#textfield').val() + "&picture=MyUrl/images/logo.png&name=FutureZoom&link=MyUrl",
type: 'POST',
success: function (resp) {
$('#ValidationMessage').html(' Post has been shared on your wall!')
.css('color', 'green');
setTimeout(function () {
$('#ValidationMessage').html('');
}, 3000);
},
error: function (request, status, error) {
alert("Facebook Error : \n" + request.responseText + '\n' + status + '\n' + error);
}
});
}
}, { scope: 'publish_stream' });
}
else {
$('#ValidationMessage').html(' Please write something to share!')
.addClass('red');
}
});
Above is working fine in Firefox browser but problem is with IE and Chrome.
In Chrome, above code posts the comment on wall but when returns, it goes into error block instead of success. Below is the error getting in chrome.
Facebook Error:
{
"id": "100002506055900_30229318964214"
}
parseerror
SyntaxError: Unexpected token:
And in IE, nothing happens. Neither posts the comment nor returns in error/success block.
What could be reason?
Instead of doing a AJAX call to post something to the user's timeline, you should use the FB.api function in the Facebook JavaScript SDK instead. It simplifies the process:
FB.api('/me/feed', 'post', { message: body, picture: pic }, function(response) {
if ( !response || response.error ) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
You can see the documentation for the JS call here: http://developers.facebook.com/docs/reference/javascript/FB.api/
You will be able to reduce your code quite a bit by using this method.

Resources