Plupload Overall Progress issue - javascript

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;
}
});
},

Related

Download Base64 image through javascript

I am working on an image panel that displays the image titles and a link to download the image. I have an onclick function that gathers the base64 data from the database and then 'decodes' it. However, when I decode it I'm getting back a string of Chinese text..which is obviously not what I'm looking for.
$(document).ready(function() {
$('.downloadAttachment').on('click', function() {
var documentId = $(this).attr("data-id");
console.log(documentId)
$.ajax({
dataType: 'json',
//data: id,
async: false,
type: 'GET',
//url: baseUrl + 'rest/incdDocument/getAll?branchCode=' + brCode + '&receivedDate=' + receiveDate + '&complaintID=' + cId + '&incidentID=' + incidentId+ '&documentID='+documentId,
url: baseUrl + 'rest/incdDocument/get?branchCode=009&receivedDate=03/10/2017&complaintID=170&incidentID=3'+'&documentID='+documentId,
success: function(data) {
if (data) {
var image = Base64.decode(data.data);
window.open(image, '_blank');
}
},
error: function(request, status, error) {
console.log(error)
}
});
return false;
})
});
Is there a better way to extract this data and actually turn it into an image?
Searching for like this ?
var image = new Image();
image.src = data; (complete base64 sting with imagetype)
Download Image
Make a download.php file with return the a image with
header('Content-type:image/png'); or other image type

IF statement to check if file exists in path not working

I am trying to check if a file from a multiple upload exists in the path already, if so i want to chuck out a validation error. Its the else if part that is not working. The number directory gets created in the ajax controller server side, but i want to do a check before they upload further files with the same name to that directory. Is this possible? What am i doing wrong here?
function makeProgress(number){
var url = getRelativeURL("web/fileUpload");
var formData = new FormData();
formData.append('number', number);
fls = document.getElementById("attachmentFileUploadInput").files; //number of files...
console.log(fls);
var location = "C:/temp/" + number + "/";
console.log(location);
// maximum number of files at a time is 10
if(fls.length >= 11){
FileUploadLengthVisible(true);
return false;
}
var j;
for(j=0;j<fls.length;j++){
if (fls[j].size > 5000000) //5MB size per file
{
FileUploadSizeVisible(true);
return false;
}
else if (location + fls[j] == true)
{
alert("file exists");
return false;
}
else
{
formData.append('files[]', fls[j]); //note files[] not files
$.ajax({
url : url,
data : formData,
processData : false,
cache: false,
contentType: false,
type : 'POST',
success : function(data) {
FileUploadVisible(true);
$('#attachmentModal').modal('hide')
$(':input','#attachmentModal').val("");
$("#pbarmain").hide();
$("#pbar").hide();
$("#actionPlanDiv").hide();
setObjectEnabled('#Upload',false);
},
error : function(err) {
FileUploadErrorVisible(true);
}
});
console.log('loop each file working');
}
}
console.log("form data " + formData);
}

Large file upload Failed via ajax call

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.

Link not opening after streaming data of the document down

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.

Why the text before Ajax call is not display?

function pdfToImgExec(file, IsfirstLogging, folder, round) {
alert(file);
var postString = file + '&' + IsfirstLogging + '&' + folder + '&' + round;
var errorMsg = (folder == 'Incoming' ? '<p>error in incoming folder</p>' : '<p>error in other folder</p>');
$.ajax({
type: "POST",
cache: false,
async: false,
url: "pdfToImgExec.php",
data: {
"data": postString
},
dataType: "html",
beforeSend: function () {
alert(file + 'a');
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
},
success: function (data) {
if(data == '1') {
$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
} else if(round < 4) {
$('#pdfToImgResult').html('<p>Fail to convert , retry ' + round + ' round <img src="loading.gif" height="20" width="20"/></p>');
round++;
pdfToImgExec(file, 'false', folder, round);
} else {
folder == 'Incoming' ? tempFailIncomingFiles.push(file) : tempFailResultFiles.push(file);
}
},
error: function (x, t, m) {
$('#pdfToImgResult').html(errorMsg);
alert(t);
releaseBtn();
}
});
}
The problem of this ajax call is I can alert the (file + 'a') in the beforeSend function , but the
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
is not working, it will not display anything but only jumped to the
$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
after the ajax call is finished.
Is it due to async:false? How to fix the problem ? thanks.
It's because you're using async: false,, so the function blocks until the request is complete, preventing a redraw until everything is done.
You seem to be all set up with callbacks, so there doesn't seem to be any reason to make a blocking xhr request. Just remove the async: false,, and you should be all set.
Here's a quick example of how to deal with asynchronous code. I've removed most of your code to keep it brief.
// --------------------------------new parameter-------------v
function pdfToImgExec(file, IsfirstLogging, folder, round, callback) {
// your code...
$.ajax({
type: "POST",
cache: false,
// async: false, // Remove this line!
url: "pdfToImgExec.php",
data: {
"data": postString
},
dataType: "html",
beforeSend: function () {
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
},
success: function (data) {
// your code...
// Invoke the callback, passing it the data if needed
callback(data)
},
error: function (x, t, m) {
// your code;
}
});
}
When you call pdftoImgExec, pass a function as the last parameter that will be invoked when the response is complete. That function is where your code resumes.
pdfToImgExec(..., ..., ..., ..., function(data) {
// resume your code here.
alert(data);
})

Categories

Resources