Now I am working on File upload. So I had written a piece of code using ajax call. This is working perfectly when I am uploading files (GB) from my local server.
$.ajax({
type: "POST",
url: "process/uploadFlatFile.htm",
enctype : 'multipart/form-data',
//timeout: 0,
crossDomain: true,
data : formData,
processData: false,
contentType: false,
cache: false,
dataType: 'json',
xhr: function() {
myXhr = $.ajaxSettings.xhr();
//myXhr = new XMLHttpRequest();
console.log("myXhr: " + myXhr.upload);
if(myXhr.upload){
console.log("adding progress event listener");
myXhr.upload.addEventListener('progress', showProgress, false);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
},beforeSend: function(xhr, opts) {
console.log("beforeSend:xhr: " + xhr + ", opts: " + opts);
currXhr = xhr;
showProgressBar();
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
$(cancelSelector).removeAttr('disabled');
},
success: function(result,status,xhr) {
console.log("success:result: " + result);
console.log("success:status: " + status);
console.log("success:xhr: " + xhr);
var percentVal = '100%';
bar.width(percentVal);
//$("#fountainGG").hide();
percent.html(percentVal);
$.unblockUI({
onUnblock: function(){
if(result=="success"){
console.log("SUCCESS PART :")
alertMessage("Success","File Uploaded Successfully","info");
setTimeout(function(){
window.location.href = "processFlow.htm";
//newProcessClicked('yes'); closeConDiv()
}, 2000);
}else{
alertMessage("Error","Error in upload. Try Again !","info");
}
}
});
},
complete: function(xhr,status){
console.log("COMPLETE PART :")
console.log("complete:status: " + status + ", xhr: " + xhr);
$('#btnGoUpload').prop('disabled', false);
},
error: function(xhr, statusText, err) {
$.unblockUI();
console.log("statusText: " +statusText);
console.log("error: " + err);
var msg = "Error in uploading file. Try Again !";
if (err == "abort"){
msg = "File upload aborted.";
}
alertMessage("Error",msg,"info");
}
});
But when I am uploading GB (above 30 Gb) files from public server it's going to error part of ajax call after couple of time. I think it is connection time out problem? If it is connection time out problem , how can I resolve it?
You can workaround a possible time out limit with this command, to be put in the begin of your php receiver script :
ini_set('max_execution_time', 0);
To increase the max upload size, that can also block you, you need to set the value of upload_max_filesize and post_max_size in your php.ini :
; Maximum allowed size for uploaded files.
upload_max_filesize = 40M
; Must be greater than or equal to upload_max_filesize
post_max_size = 40M
Edit and restart your web server.
Related
I have below code in before upload event for a Plupload control in my aspx page which has three upload control for upload images. my problem is when "Validate_Img_File_Name.ashx" returns not success output and stop the specific file upload the overall progress bar and the progress percentage is not finishing at 100%. function "_updateTotalProgress:" in jquery.ui.plupload.js do the overall progress I guess, but I have no idea of how to overcome this issues since my knowledge of java is zero. how can I get the correct overall progress ? your help is highly appreciated.
BeforeUpload: function (up, file) {
// Called right before the upload for a given file starts, can be used to cancel it if required
//log('[BeforeUpload]', 'File: ', file);
$.ajax({
url: "../Validate_Img_File_Name.ashx",
type: "POST",
datatype: 'text',
data: { filename: file.name },
cache: false,
}).done(function (data) {
if (data == "SUCCESS") {
up.settings.url = '/bulk_img_uploader.ashx';
file.status = plupload.UPLOADING;
up.trigger("UploadFile", file);
up.settings.url = '';
log('File:', file, '- OK');
} else {
//alert(file.name + " " + "fail");
up.stop();
file.status = plupload.FAILED;
up.trigger('QueueChanged'); //Line A
up.trigger('UploadProgress', file); // Line B
up.start();
log('File:', file, ' - ' + data);
return false;
}
});
},
I think I am missing some code on the JavaScript side. I am downloading the documents for each request. When the user clicks on the link, I go get the document data and stream it down. I see on Fiddler that the data is coming down, but the .txt document link is not opening.
[HttpGet]
public HttpResponseMessage GetDataFiles(Int64 Id)
{
var results = context.PT_MVC_RequestFile.Where(x => x.RowId == Id).FirstOrDefault();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
if (results != null)
{
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(results.Data);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = results.FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = results.Data.Length;
}
}
catch (EntityException ex)
{
throw new EntityException("GetFiles Failed" + ex.Message);
}
return response;
}
Firstly, I downloaded all the documents for that request, and if the user clicks on the file, I call the download stream action.
$.ajax({
url: url,
type: 'GET',
// data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
if (data != "") {
$("#fileLength").val(data.length);
// alert(data.length);
$.each(data, function (i, item) {
var newDiv = $(document.createElement('div')).attr("id", 'file' + i);
newDiv.html("<input id=\"cb" + i + "\" type=\"checkbox\"> <a href=\"#\" onclick=\"GetData('" + item.RowId + "','" + item.mineType + "')\" >" + item.FileName + "</a>");
newDiv.appendTo("#fileRows");
});
} else {
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I think I am missing something after success though. Somehow it downloads the data, but the link does not open. Could it be the content type is not set, or that it thinks it is JSON data? Help with some ideas please.
Here is the link:
function GetData(rowId,mineType) {
// alert(mineType);
var url = "api/MyItemsApi/GetDataFiles/" + rowId;
$.ajax({
url: url,
type: 'GET',
//data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
You can't easily download a file through an Ajax request. I recommend to post the data to a blank page from a form, instead of the Ajax (you can populate that form and post it via jQuery if you need to). If you're interested, I could guide you through it, just let me know.
If you still want to download from Ajax, I suggest you refer to this post.
I am working ona application, when the user clicks on the "save" button in the application, it saves the information and restarts the server.
The form has to be successfully submitted before ajax success will fire. If the information is saved correctly from the form, i get a 200 success message from the server.
If there is success(200) the server restarts, when the Server restarts or is restarting it gives a 500 internal server message, it take about 30 to 40 sec or more to restart the server so i have await time for 30 sec..
Once the server restarts it gives a 200 success server message.
Currently I am using Ajax call 2 to check for success for data submission for server restart and the other 1st Ajax call 1 to recheck the server is restarting and the data has been updated.
I have currently the following 2 ajax codes
Ajax call 1
$.ajax({
// dataType : 'jsonp',
//jsonp : 'js',
url: "some.json",
beforeSend : function(jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(" 500 top data still loading"+ jqXHR + " : " + textStatus + " : " + errorThrown);
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete : function(jqXHR, textStatus) {
alert(" complete "+ jqXHR + " : " + textStatus);
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function(data, textStatus, jqXHR){
alert(" success "+ jqXHR + " : " + textStatus);
console.info('in success');
console.log(data, textStatus, jqXHR);
}
});
Ajax call 2
$(function () {
$("#save").click(function () {
$.ajax({
type: "POST",
url: "some.json",
data: json_data,
contentType: 'application/json',
success: function (data, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
alert("Your changes are being submitted: " + textStatus + " : " + xhr.status);
$('#myModal').modal('hide');
/*
This gives a messagthat the server is restarting iina modal window and waits for 30sec
*/
$('#myModal-loading').modal('show');
/*** Re check bit by Ryan ***/
var restartCheck = window.setInterval(
$.ajax({
// dataType : 'jsonp',
//jsonp : 'js',
url: "../../../../../rest/configuration",
beforeSend: function (jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" 500 top data still loading " + jqXHR + " : " + textStatus + " : " + errorThrown);
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
alert(" complete " + jqXHR + " : " + textStatus);
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function (data, textStatus, jqXHR) {
window.clearInterval(restartCheck);
alert(" success " + jqXHR + " : " + textStatus);
console.info('in success');
console.log(data, textStatus, jqXHR);
}
}), 30000); //This will call the ajax function every 3 seconds until the clearInterval function is called in the success callback.
/*** recheck bit **/
setTimeout(function () {
location.reload(true);
}, 30000);
$('<div id="loading">Loading...</div>').insertBefore('#myform-wiz');
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText + " - " + errorThrown + " : " + jqXHR.status);
}
});
});
});
});
Is it possible to re-check continuously within success in Ajax call 2 , if the server is giving a 500 error message to check for restart of server and recheck for success for 200 before redirecting back to the updated page?
You could probably just use a setInterval. Don't forget to clear it in the success callback.
var restartCheck = window.setInterval(
$.ajax({
// dataType : 'jsonp',
//jsonp : 'js',
url: "some.json",
beforeSend : function(jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(" 500 top data still loading"+ jqXHR + " : " + textStatus + " : " + errorThrown);
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete : function(jqXHR, textStatus) {
alert(" complete "+ jqXHR + " : " + textStatus);
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function(data, textStatus, jqXHR){
window.clearInterval(restartCheck);
alert(" success "+ jqXHR + " : " + textStatus);
console.info('in success');
console.log(data, textStatus, jqXHR);
}
})
, 3000); //This will call the ajax function every 3 seconds until the clearInterval function is called in the success callback.
Well, my idea could be to put your ajax request inside a method and do the following:
1. Send the request to save your data and restart server.
2. In the process you need to validate that the data is not repeated in the database.
3. If there is an error present then the method is executed again and again but the data is not double saved due to the validation implemented in number 2 and only the server gets restarted.
To start all this, I made a simulation of your situation. Just to know, I don't know which kind of server language are you using (because it is not specified in the question tags) but I will use PHP for making this easy...
The following example makes this:
A user inputs his/her name inside a textbox and then when he/she clicks the "Save" button, the data will be send to the server and, after 50s the callback will be returned to client side. But, if the input name is oscar then the server will return a 500 HTTP error and you will see how the code gets executed again to try "restarting" the server one more time (remember it's a simulation). Otherwise everything will return a 200 HTTP OK.
Please read all comments inside the code, check the browser console and if you can... test it!
index.php: This is the main page.
<html>
<head>
<title>Simulation</title>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn').click(function() {
save();
});
});
function save() {
$('#msg').text('Please wait while restarting the server...').show();
$('#btn').hide();
$.ajax({
type: 'POST',
url: 'process.php',
data: $('form').serialize(),
statusCode: {
500: function() {
console.log('500 HTTP error present, try again...');
/* Invoke your method again to try restarting the server.
* To avoid double save of 'name' variable please
* check the first comments at 'process.php' file.
*/
$('#msg').text('Re-trying to restart the server...');
/* While waiting check the browser console and look that
* the save method is getting invoked again and again until
* you change the name from 'oscar' to another.
*/
save();
},
200: function() {
$('#msg').text('Server restarted!').fadeOut('slow');
$('#btn').fadeIn();
}
}
});
};
</script>
<body>
<span id="msg"></span>
<br/>
<form>
Name: <input type="text" name="name" id="name"/><br/>
<input type="button" name="btn" id="btn" value="Save"/>
</form>
</body>
</html>
process.php: This file will receive the ajax request from jQuery (Just to know I am using version 1.7.2).
<?php
if(isset($_POST['name'])){
$name = $_POST['name'];
/* TODO: In this case and at this point, you need to save the
* name into DB but only if it doesn't exist because if 500 error
* is present, then the request have to be validated again to
* just restart the server (maybe doing some if/else to evaluate) and
* don't make a double save.
*/
/* TODO: restart the server...
* I will simulate the long wait for the server to respond (50s)
* using sleep before sending back the name variable to client side.
*
* But!
* I will do a tricky thing at this point. If the name is 'oscar' then
* I will produce a 500 HTTP error to see what happens at client side...
*/
/* Wait first 27s */
sleep(27);
/* If $name is 'oscar' then return 500 error */
if($name == 'oscar') {
throw new Exception('This is a generated 500 HTTP server error.');
}
/* If $name != 'oscar' then wait 23s to simulate
* the long time for restarting server...
*/
sleep(23);
flush();
/* Retun $name in the callback */
echo $name;
}
?>
Hope this helps :-)
I searched similar questions but never found a proper answer. I am making app for multiple platforms using phonegap and JQM. I made index.html, which is "login page", with similar call. Index's call works, but the one below never gets called on my android device, even though it works both on chrome and safari.
I checked sever logs and there are no problems with "login", but as I said, there is no request from my android device when function below should be called.
//document.addEventListener("deviceready", onDeviceReady, true);
$( document ).bind( "mobileinit", function(){
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.loadingMessageTextVisible = true;
$.mobile.showPageLoadingMsg();
console.log('Page Started');
})
//var onDeviceReady = function(){
$( document ).ready(function (){
console.log('Start');
//$.support.cors = true;
//$.mobile.allowCrossDomainPages = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://ip/services/rest/contact/list',
callback: 'jsonpCallback',
jsonpCallback: 'jsonpCallback',
jsonp: '_jsonp',
contentType: 'application/json',
dataType: 'jsonp json',
timeout : 10000,
success: function(data){
var html ='';
console.log('Success');
$.each(data.response, function(key, value) {
html += '<li><a class=contact href="#" id="' + data.response[key].id + '" ><h1>' + data.response[key].label + '</h1><p>'+ data.response[key].customerName + '</p><p>' + data.response[key].phone + ', ' + data.response[key].email + '</p></a></li>';
$('#ul_id').append($(html));
html='';
console.log('conatct');
});
$('#ul_id').trigger('create');
$('#ul_id').listview('refresh');
},
error: function (xhr, ajaxOptions, thrownError){
alert("Status: " + xhr.status + ", Ajax option: " + ajaxOptions + ", Thrown error: " + thrownError);
//location.reload();
console.log('Blad');
},
});
});
What is the access origin value in your Android project config.xml file ?
your value should be as below :
<access origin=".*"/>
There was a problem with placing script and specific way that jqm work.
I make function in Aspx page and call this function from java script , Now i want to download files through Java script. But Download Dialog Doesn't Open.....
Download.Aspx:
string pid = Request.QueryString["Did"].ToString();
DataTable dt;
dt = common.GetFilePath(Convert.ToInt64(pid));
FilePath = dt.Rows[0]["FilePath"].ToString();
FileName = dt.Rows[0]["FileName"].ToString();
FilePath = System.Web.HttpContext.Current.Server.MapPath("~//" + FilePath + "");
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "");
Response.WriteFile(FilePath);
Response.End();
Jquery:
function DownloadAttach(pid){
$.ajax({ type: "POST",
url: "http://localhost:1988/DownLoad.aspx?Did=" + pid,
dataType: "xml",
processData: true,
//error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
success: function(xml) {
//ShowMsg("projSaveMsg", "Attachment Deleted.");
}
});
}
You don't want to make an AJAX call for this - just redirect the browser:
function DownloadAttach(pid){
window.location = "http://localhost:1988/DownLoad.aspx?Did=" + pid;
}