I am uploading the multiple files through ajax, where i need to keep a progress bar. I am able to get the progress complete status only after all the process done, so i need to keep the progress bar showing status during upload.
Here when I clicking the 'btnEditImageSave' button, I am checking whether the existing file is getting delete and uploading in if condition.
In that storing the uploading file and passing it for uploading process in ajax complete function. In it that i have included the progress bar code to show the progress status, but its showing only after the all the process completes.
$('#btnEditImageSave').unbind().click(function (event) {
$('#progressBardiv').css('width', '0');
$('.progressBardiv').text('');
if (uploadedfiles.length > 0 && deleteFiles.length == 0) {
if (editStoredFiles.length > 0) {
var files = new FormData();
for (var i = 0; i < editStoredFiles.length; i++) {
if (editStoredFiles[i].size > 0) {
files.append(editStoredFiles[i].name, editStoredFiles[i]);
}
}
uploadedfiles = [];
files.append('SerialNumber', editSerialNumber);
$.ajax({
type: "POST",
url: productionBaseUrl + '/Home/UploadDockingStationFiles',
data: files,
contentType: false,
processData: false,
async: true,
complete: function () {
uploadedfiles = [];
$('#editfileupload').val();
$.ajax({
type: "POST",
url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
FileSpinTimer: $('#txtEditTimer').val(),
IsHDMIUpdate: isHDMIUpdate
}),
/*----My Progress Bar code----*/
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total;
percentComplete = parseInt(percentComplete * 100);
$('#progressBardiv').text(percentComplete + '%');
$('#progressBardiv').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
complete: function () {
$('#loading-popup').hide();
$('#divEditDockingStationImages').dialog("close");
$.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
return false;
}
});
}
});
}
}
else {
$('#loading-popup').hide();
$.popup('<pre>Message</pre>', "Please Select a File.", 'OK');
return false;
}
}
<div class="progress">
<div id="progressBardiv" class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="">
<span class="sr-only"></span>
</div>
</div>
For those in 2022 still looking how to measure an XHR upload operation progress, there's an API called ProgressEvent (https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent) with broad support of major browsers. No need to use custom plugins.
Also, a detailed post with examples on how to use this can be found here: https://medium.com/swlh/uploading-files-with-progress-monitoring-in-vanillajs-angular-and-vuejs-625e2491821
You can use plUpload plugin to upload files..
Follow this link:https://www.plupload.com/docs
it has its own event for progressbar...
See the sample code below...
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
container: document.getElementById('container'), // ... or DOM Element itself
url: "//",
filters: {
max_file_size: '500mb',
mime_types: [
{ title: "PDF files", extensions: "pdf" }
]
},
flash_swf_url: '/plupload/js/Moxie.swf', // Flash settings
silverlight_xap_url: '/plupload/js/Moxie.xap', // Silverlight settings
init: {
PostInit: function () {
// whereas filelist is the divid which contains uploaded file names....
document.getElementById('filelist').innerHTML = '';
uploader.start();
},
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
document.getElementById('filelist').innerHTML +=
'<div id ="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) +
') <b></b> Remove</div>' +
'<div class="progressbar" id ="progressBar_' + file.id + '"> <div class="mybar" id="myBar' + file.id + '"></div></div>';
});
},
UploadProgress: function (up, file) {
var $progressId = $("#filelist div#progressBar_" + file.id + " div.mybar");
$progressId.css('width', file.percent + '%');
//To Remove 'Remove Link' while file is in uploading state.
$("#filelist div#" + file.id).find('a.remove').remove();
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
FileUploaded: function (up, file, ServerResponse) {
var response = JSON.parse(ServerResponse.response);
},
UploadComplete: function (up, file) {
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
uploader.init();
I have used in my project have a look on snapshot below,
if (deleteFiles.length > 0 && uploadedfiles.length > 0) {
$.ajax({
type: "POST",
url: productionBaseUrl + "/Home/DeleteDockingStationFiles",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: JSON.stringify({
serialNumber: editSerialNumber,
files: deleteFiles
}),
complete: function () {
deleteFiles = [];
if (editStoredFiles.length > 0) {
var files = new FormData();
for (var i = 0; i < editStoredFiles.length; i++) {
if (editStoredFiles[i].size > 0) {
files.append(editStoredFiles[i].name, editStoredFiles[i]);
}
}
uploadedfiles = [];
files.append('SerialNumber', editSerialNumber);
$.ajax({
type: "POST",
url: productionBaseUrl + '/Home/UploadDockingStationFiles',
data: files,
contentType: false,
processData: false,
async: true,
xhr: function (data) {
var xhr = new window.XMLHttpRequest(data);
xhr.upload.addEventListener("progress", function (event) {
if (event.lengthComputable) {
var percentComplete = event.loaded / event.total;
percentComplete = parseInt(percentComplete * 100);
$('#progressBardiv').text(percentComplete + '%');
$('#progressBardiv').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
beforeSend: function () {
uploadedfiles = [];
$('#editfileupload').val();
$.ajax({
type: "POST",
url: cloudServerUrl + "/api/dockstation/updatefiledisplaytimer",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
SerialNumber: $('#ddlEditDockingStationSerialNumber').val(),
FileSpinTimer: $('#txtEditTimer').val(),
IsHDMIUpdate: isHDMIUpdate
}),
complete: function () {
$('#loading-popup').hide();
$('#divEditDockingStationImages').dialog("close");
$.popup('<pre>Message</pre>', "Image Configuration Updated Successfully.", 'OK');
return false;
}
});
}
});
}
}
});
}
Related
i created js code that when user change some file input its send POST request to server and upload the file.
but the JS side very slow if i try to upload 4MB image, the PHP file start after 1 min
i tried to add some log to the php file and i saw that its another to the start of the file after 1 min.
this is the JS code:
$("input[name='upload-avatar-input']").on('change', function () {
const me = this;
setLoading(true);
if (this.files.length > 0) {
if (!window.FormData) {
alert("Error!");
return false;
}
const url = $(this).closest("form").attr("action");
$.ajax({
url: url,
method: 'POST',
dataType: 'json',
data: new FormData(this.form),
contentType: false,
processData: false,
beforeSend: function () {
if ($(".myformPop").length <= 0)
$("body").append('<div class="myformPop"><i class="close">close</i><div class="heading"></div><div class="output"></div></div>');
},
success: function (data) {
if (data.success === 1) {
const t = new Date().getTime();
const img = $(me).closest("form").find("#avatarCircle .inner");
img.css("background-image", "url('" + data.url + "?t=" + t + "')");
$('.delete-avatar-button').attr("disabled", false);
} else {
const pop = $(".myformPop");
pop.find("div.heading").html(data.heading);
pop.find("div.output").html('<ul>' + data.message + '</ul>');
$.getScript("assets/js/jquery.bpopup-0.7.0.min.js", function (bpop_data, textStatus, jqxhr) {
pop.bPopup({
bmodalClose: false,
onClose: function () { }
});
});
}
setLoading(false);
},
complete: function () { },
error: function () {
setLoading(false);
}
});
} else {
setLoading(false);
}
});
and the url variable is some php file that upload the file, but the file started after 1 min, so the problem in the js code.
what can i do with large files like 4MB - 8MB (its normal size of mobile hd images)
tnx
I'm sending one file to a PHP file through an AJAX POST request but it's sending an empty string even though if I tried to send the name only or size etc. it works just fine.
Am I doing something wrong here?
$(document).ready(function() {
let validExt = ['jpg', 'jpeg', 'png']
$('#file-upload').change(function() {
var extension = this.files[0].type.split('/')[1]
if (validExt.indexOf(extension) == -1) {
swal({
title: "!الملف غير صالح " + "(" + this.files[0].type.split('/')[1] + ")",
text: "('jpg' , 'jpeg' , 'png') الصيغ المقبولة",
icon: "warning",
button: "رجوع",
});
return false;
} else if (this.files[0].size > 2000000) {
swal({
title: "!الملف غير صالح" + "(" + (this.files[0].size / 1024 / 1024)
.toFixed(2) + "MB)",
text: "لا يمكن ان يزيد حجم الملف عن 2 ميغابايت",
icon: "warning",
button: "رجوع",
});
return false;
}
var file_data = $('#file-upload').prop('files');
var form_data = new FormData();
form_data.append('files', file_data);
$.ajax({
url: "edit-product.php",
type: "POST",
data: file_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(form_data);
// $(document).ready(function(e) {
// setTimeout(function() {
// location.reload();
// }, 2000)
// });
}
});
});
});
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file-upload">
The code below is working fine to upload files to SPO through RestAPI. No feedback is received on file upload progress. An alert is thrown once the upload is complete.
I would like to have a progress bar to display the upload percentage and reload this upload page while clicking OK to the successful alert message.
Kindly assist.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function () {
init();
});
function init(){
$("#btnUploadFiles").click(function(){
var files=$("#inputTypeFiles")[0].files;
uploadFiles(files[0]); // uploading singe file
});
}
function uploadFiles (uploadFileObj) {
var fileName = uploadFileObj.name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary="TEST";
var folderName = "";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&#target='" + targetUrl + "'";
uploadFileToFolder(uploadFileObj, url, function (data) {
var file = data.d;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
departname: $("#departname").val(), //meta data column1
Filename: $("#filename").val(), //meta data column2
ACFTREG: $("#ACFTREG").val(), //meta data column3
Date: $("#datepicker").val() //meta data column4
};
url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";
updateFileMetadata(url, updateObject, file, function (data) {
alert("File uploaded & metadata updation done successfully");
}, function (data) {
alert("File upload done but metadata updating FAILED");
});
}, function (data) {
alert("File uploading and metadata updating FAILED");
});
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
var getFile = getFileBuffer(fileObj);
getFile.done(function (arrayBuffer) {
$.ajax({
url: apiUrl,
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
});
}
function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
$.ajax({
url: apiUrl,
type: "POST",
async: false,
data: JSON.stringify(updateObject),
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Content-Type": "application/json;odata=verbose",
"X-Http-Method": "MERGE",
"IF-MATCH": file.ListItemAllFields.__metadata.etag,
},
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
function getItems() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('L%20-%20MDB%20-%20ACFTREG')/items?$Select=Title&$top=2000",
type: "GET",
headers: {
"accept": "application / json;odata = verbose",
},
success: function(data) {
var results = data.d.results;
var options = "";
for(var i = 0; i < results.length; i++){
options = options + "<option value='" + results[i].Title + "'>" + results[i].Title + "</option>";
}
$("#ACFTREG").append(options);
},
error: function(error) {
alert(JSON.stringify(error));
}
});
}
$( function() {$( "#datepicker" ).datepicker(
{
changeMonth: true,
changeYear: true
}
);} );
</script>
Select File:<input type="File" id="inputTypeFiles" /><br />
Departname: <input id="departname" type="textbox"/><br />
Date: <input type="text" id="datepicker" autocomplete="off" name="hidden"><br />
Filename: <input id="filename" type="textbox"/><br />
ACFTREG: <select id="ACFTREG" class="select">
<option selected="selected">Select</option><br />
<input type="button" id="btnUploadFiles" value="Upload"/><br />
Inside the $.ajax({}) function, you can add the xhr setting inside the ajax.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
// Place upload progress bar visibility code here
}
}, false);
return xhr;
},
type: 'POST',
//add the rest of ajax settings
check this link for ajax documentation
jQuery/ajax
check this link for example on upload progress
jQuery-upload-progress/example
I got a progress bar that runs after clicking submit.
The app will then process the background task and update the progress bar.
The question is how can I show the download button after the progress bar hits 100% instead of showing the button when the progress bar starts updating?
$('form').on('submit', function(event) {
event.preventDefault();
var formData = new FormData(this);
// add task status elements
div = $('<div class="progress"><div></div><div>0%</div><div>...</div></div>');
$('#progress').append(div);
// progress bar
var nanobar = new Nanobar({
bg: '#03adff',
target: div[0].childNodes[0]
});
$.ajax({
type: 'POST',
url: '/longtask',
data: formData,
processData: false,
contentType: false,
success: function(data, status, request) {
status_url = request.getResponseHeader('Location');
update_progress(status_url, nanobar, div[0]);
},
complete: function() {
$("#dl").css("display", "block");
},
error: function() {
alert('Unexpected error');
}
});
})
function update_progress(status_url, nanobar, status_div) {
// send GET request to status URL
$.getJSON(status_url, function(data) {
percent = parseInt(data['current'] * 100 / data['total']);
nanobar.go(percent);
$(status_div.childNodes[1]).text(percent + '%');
$(status_div.childNodes[2]).text(data['status']);
if (data['state'] != 'PENDING' && data['state'] != 'PROGRESS') {
if ('result' in data) {
// show result
$(status_div.childNodes[3]).text('Result: ' + data['result']);
} else {
// something unexpected happened
$(status_div.childNodes[3]).text('Result: ' + data['state']);
}
} else {
setTimeout(function() {
update_progress(status_url, nanobar, status_div);
}, 1000);
}
});
}
Assuming #dl is you download button.
You could just move the $("#dl").css("display", "block"); into your update_progress function:
$('form').on('submit', function(event) {
event.preventDefault();
var formData = new FormData(this);
// add task status elements
div = $('<div class="progress"><div></div><div>0%</div><div>...</div></div>');
$('#progress').append(div);
// progress bar
var nanobar = new Nanobar({
bg: '#03adff',
target: div[0].childNodes[0]
});
$.ajax({
type: 'POST',
url: '/longtask',
data: formData,
processData: false,
contentType: false,
success: function(data, status, request) {
status_url = request.getResponseHeader('Location');
update_progress(status_url, nanobar, div[0]);
},
error: function() {
alert('Unexpected error');
}
});
})
function update_progress(status_url, nanobar, status_div) {
// send GET request to status URL
$.getJSON(status_url, function(data) {
percent = parseInt(data['current'] * 100 / data['total']);
nanobar.go(percent);
$(status_div.childNodes[1]).text(percent + '%');
$(status_div.childNodes[2]).text(data['status']);
if (data['state'] != 'PENDING' && data['state'] != 'PROGRESS') {
if ('result' in data) {
// Show download button once done
$("#dl").css("display", "block");
// show result
$(status_div.childNodes[3]).text('Result: ' + data['result']);
} else {
// something unexpected happened
$(status_div.childNodes[3]).text('Result: ' + data['state']);
}
} else {
setTimeout(function() {
update_progress(status_url, nanobar, status_div);
}, 1000);
}
});
}
I have this chunk of code:
$.ajax({
type: "POST",
async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {
}
}]
});
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {}
}]
});
}
});
When the ajax return success it displays the dialog box for a whole 2 seconds or so (not long enough for a user to read the message that it contains) then closes it. Using chrome's debugger, I've determined that it runs out of scope without waiting for a confirmation on the dialog box inside the success function. Does anyone know how I would go about halting the code until the user clicks ok?
Here is the full chunk of code for that ajax call..
var leZDB = null;
function zipSelectedAttachments() {
var ids = getSelectedTaskIDs();
if (ids.length > 0) {
leZDB = $.Zebra_Dialog('Do you want to zip the attachment(s)?', {
'type': 'question',
'title': 'Confirmation',
'buttons': ['Yes', 'No'],
'onClose':function (caption) {
if(caption = 'Yes') {
LinkAndPass(ids);
}
}
});
} else {
$.Zebra_Dialog('No attachments are selected.', {
'type': 'error',
'title': 'Error',
'buttons': [
{ caption: 'Ok', callback: function () { } }
]
});
}
}
function LinkAndPass(ids) {
leZDB.close();
if (true)
{
SendIDSForZipping(ids);
}
}
function SendIDSForZipping(ids) {
var csList = '';
var userID = $('#hiduserID').val();
for (var i = 0; i < ids.length; ++i) {
csList += ids[i] + ',';
}
var $this = $(this);
$this.die('click');
$.ajax({
type: "POST",
//async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID+ "'}",
contentType: "application/json; charset=utf-8",
context:this,
dataType: "json",
success: function (data) {
var hasClickedOK = false;
var hasDisplayed = false;
if (!hasDisplayed) {
hasDisplayed = true;
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
hasClickedOK = true;
}
}
]
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
}
}
]
});
}
});
}
The getSelectedIDs() returns an array of numbers.
The Code behind returns a string.
try asyn:false in $.ajax({
type: "POST",
async: true
});
The problem consisted of the web method being called from the code behind. A faulty piece of logic caused it to refresh the page, instantly closing the box.