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
Related
We have more option into DropZone.js such as removedFile. In this Javascript script, I try to remove DropZone thumbnail after deleting file from server. Removing file from server works fine, but I can't detach thumbnails
<script type="text/javascript">
var DropzoneUp = function () {
var _componentDropzone = function () {
if (typeof Dropzone == 'undefined') {
console.warn('Warning - dropzone.min.js is not loaded.');
return;
}
// Multiple files
Dropzone.options.dropzoneMultiple = {
paramName: "file",
//...
params: {
prefixFile: '{{csrf_token()}}'
},
removedfile: function (file) {
jQuery.ajax({
//...
dataType: "json",
success: function (data) {
}
});
}
};
};
return {
init: function () {
_componentDropzone();
}
}
}();
DropzoneUp.init();
</script>
How can I do that and how can I remove thumbnails?
My problem solved by this code in success call back function:
removedfile: function (file) {
jQuery.ajax({
//...
type: "POST",
dataType: "json",
success: function (data) {
let _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});
},
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;
}
});
}
});
}
}
});
}
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);
}
});
}
Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.
I am using following code to fetch and cache data from a ASP.NET handler. The problem is that whenever I cache data using a button click its working fine, but I want this to happen at document.ready() event. When I executed this code on document.ready() event, its fetching data perfectly, but its not getting data from the cache when I reload the page.
var localCache = {
data: {},
remove: function (url) {
delete localCache.data[url];
},
exist: function (url) {
return localCache.data.hasOwnProperty(url) && localCache.data[url] !== null;
},
get: function (url) {
console.log('Getting in cache for url' + url);
return localCache.data[url];
},
set: function (url, cachedData, callback) {
cacheTime = (new Date()).getTime();
localCache.remove(url);
localCache.data[url] = cachedData;
if ($.isFunction(callback)) callback(cachedData);
}
};
var now;
var cacheTime;
var tDiff;
function getValueAtIndex(index) {
var str = window.location.href;
return str.split("/")[index];
}
//$(document).ready(function () {
$('#Button1').click(function (e) {
var url = '/Handlers/ResponseFetcher.ashx';
var topicid = "<%=desid %>";
$.ajax({
url: url,
type: "POST",
data:
JSON.stringify({ tid: topicid })
,
dataType: "json",
cache: true,
beforeSend: function () {
now = (new Date()).getTime();
if (localCache.exist(url)) {
tDiff = now - cacheTime;
if (tDiff < 20000) {
loadData(localCache.get(url));
return false;
}
}
return true;
},
complete: function (jqXHR, textStatus) {
localCache.set(url, jqXHR, loadData);
}
});
});
function loadData(data) {
console.log("now: " + now + ", cacheTime: " + cacheTime + ", tDiff:" + (cacheTime - now));
$('#responseloader').hide();
var resdata = JSON.parse(data.responseText);
$(resdata).each(function (i) {
$('#responsecontainer').append("<div>" + this.Title + "</div>");
});
}
Here tDiff will be undefined on first run. Is this the problem? or caching doesn't work if the page is reloaded? Please help!