Javascript progress bar doesn't work with Firefox - javascript

I'm currently setting up a progress bar in my website with Javascript. It works very well with Google Chrome, but not in Firefox... What's the problem ?
function uploadFile() {
var file = document.getElementById("fileToUpload").files[0];
var formdata = new FormData();
formdata.append("fileToUpload", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "send.php");
ajax.send(formdata);
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
document.getElementById("progressBar").value = Math.round(percent);
document.getElementById("status").innerHTML = Math.round(percent) + "%";
if (document.getElementById("status").innerHTML == "100%") {
document.getElementById("status").innerHTML = "Finalisation...";
}
}
function completeHandler(event) {
document.getElementById("progressBar").value = 100;
}
I expect the progress bar to work with Firefox, but it does not work at all.

Related

Use "Event" with another parameter

I need to pass the id received by the uploadFile function to the progressHandler function, and still need the "event" to work, but i can't manage to do that, can someone please help me?
function uploadFile(arquivo, id) {
alert(id)
//FLUIGC.loading('#painel_inclusao_planilha').show();
var file = _(id).files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append(id, file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
//ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", ""); // http://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
//use file_upload_parser.php from above url
ajax.send(formdata); }
function progressHandler(event) {
//_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
var percent = (event.loaded / event.total) * 100;
console.log('percent ---> ' + percent)
if (percent === 100) {
console.log('Upload concluído')
ativarBotaoUpload()
FLUIGC.loading('#painel_inclusao_planilha').hide();
}
//_("progressBar").value = Math.round(percent);
//_("status").innerHTML = Math.round(percent) + "% concluído... por favor, aguarde"; }
You might do it using anonymous callback:
function uploadFile(arquivo, id) {
alert(id)
//FLUIGC.loading('#painel_inclusao_planilha').show();
var file = _(id).files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append(id, file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", function(event) {progressHandler(event, id)}, false);
//ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", ""); // http://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
//use file_upload_parser.php from above url
ajax.send(formdata); }
function progressHandler(event, id) {
//_("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
var percent = (event.loaded / event.total) * 100;
console.log('percent ---> ' + percent)
if (percent === 100) {
console.log('Upload concluído')
ativarBotaoUpload()
FLUIGC.loading('#painel_inclusao_planilha').hide();
}
//_("progressBar").value = Math.round(percent);
//_("status").innerHTML = Math.round(percent) + "% concluído... por favor, aguarde"; }

Prevent refresh after ajax file upload with ASP Generic Handler

I am trying to upload a file to the server without refreshing page on completion. I currently managed to solve the upload part using XMLHttpRequest to the Generic Handler (.ashx). However I cannot find the solution to prevent it from refreshing, tried using event.preventDefault() and return false; on the ajax but it doesn't work.
The ajax script
$('#uploadFileButton').on('click', function (event) {
var counter;
function UploadFile() {
var files = $("#<%= file1.ClientID %>").get(0).files;
counter = 0;
// Loop through files
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "FileUploadHandler.ashx");
ajax.send(formdata);
}
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress").html(Math.round(percent) + "% uploaded... please wait");
}
function completeHandler(event) {
counter++
$("#progress").html(counter + " " + event.target.responseText);
}
function errorHandler(event) {
$("#progress").html("Upload Failed");
} function abortHandler(event) {
$("#progress").html("Upload Aborted");
}
});
The FileUploadHandler.ashx
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpPostedFile file = context.Request.Files[0];
string fname = context.Server.MapPath("~/Document/" + file.FileName);
file.SaveAs(fname);
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
And in case you need it, the index.aspx body
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="file1" runat="server" AllowMultiple="true"/>
<button id="uploadFileButton">Upload</button>
<div id="progress">
</div>
</form>
</body>
Anyone care to shed light on how to solve this?
GOT IT! Its actually the VS2017's "Enable Reload on Save" property is set to True which is the default. I followed the solution here , found it after googled "SaveAs refresh page". #RGS code IS RIGHT, its just my VS settings. Hope this helps others.
Use event.preventDetault() inside button click event. You have to call UploadFile() function inside button click event.
<script type="text/javascript">
$(document).ready(function (e) {
$('#uploadFileButton').click(function (event) {
var counter;
UploadFile();
event.preventDefault();
});
function UploadFile() {
var files = $("#<%= file1.ClientID %>").get(0).files;
counter = 0;
// Loop through files
for (var i = 0; i < files.length; i++) {
var file = files[i];
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "Handler.ashx");
ajax.send(formdata);
}
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress").html(Math.round(percent) + "% uploaded... please wait");
}
function completeHandler(event) {
counter++
$("#progress").html(counter + " " + event.target.responseText);
}
function errorHandler(event) {
$("#progress").html("Upload Failed");
}
function abortHandler(event) {
$("#progress").html("Upload Aborted");
}
});
</script>

Sending two files in a queue

Hey I have a problem with sending two files in a queque. I don't have any idea how to do that when I select 2 files, 2 were uploaded at once, and the next 2 were waiting in queue. Now when I select 4 files, 2 are sent and the next two will not send. Please look in my code. Maybe you have an idea. What I must to do that make it work in function induction ?
(function() {
var imageType = /image.*/;
function uploadFile(file, percent_info, p_bar, licznik) {
var url = "server/index.php";
if (file[licznik].type.match(imageType)) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
if (percentLoaded < 100) {
percent_info[licznik].style.width = percentLoaded + "%";
}
}
});
xhr.upload.addEventListener("load", function(e) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
percent_info[licznik].style.width = percentLoaded + "%";
});
function ready() {
return function() {
if (xhr.readyState == 4 && xhr.status == 200) {
p_bar[licznik].classList.add('trans_completed');
if (licznik < file.length){
licznik++;
}
}
};
}
xhr.onreadystatechange = ready();
xhr.open("POST", url, true);
fd.append('uploaded_file', file[licznik]);
xhr.send(fd);
}
};
var uploadfiles = document.querySelector('#file-upload');
uploadfiles.addEventListener('change', function() {
var files = this.files;
var percent_info = document.querySelectorAll('.progress_bar:not(.trans_completed) .percent');
var p_bar = document.querySelectorAll('.progress_bar:not(.trans_completed)');
/* --- Upload files to server loop --- */
(function induction(files, percent_info, p_bar) {
counter_file = 0;
counter_file_2 = 1;
function caller() {
uploadFile(files, percent_info, p_bar, counter_file);
uploadFile(files, percent_info, p_bar, counter_file_2);
}
caller();
})(files, percent_info, p_bar);
});
})();

Multiple onprogress event handlers from xhr in loop

I'm currently trying to build an ajax image uploader and I have it working except for one important part.
For each separate file I upload I would like to update a progress bar for the file. Currently it only updates the last files progress bar.
$("#upload-btn").click(function() {
console.log("Click");
for (var i = 0; i < files.length; i++) {
var fd = new FormData();
fd.append("file", files[i]);
fd.append("__RequestVerificationToken", $("input[name='__RequestVerificationToken']").val());
var xhr = new XMLHttpRequest();
xhr.open('POST', "#Url.Action("AjaxUpload")", true);
var filename = files[i].name;
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
var progressbar = $('a[data-name="' + files[i].name + '"]').siblings(".progress").find(".progress-bar");
progressbar.css("width", percentComplete + "%");
}
};
xhr.onload = function () {
console.log(this.status);
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
};
};
xhr.send(fd);
}
});
As you may have guessed from the code, I'm pretty terrible at javascript... Any help is greatly appreciated.
You need to scope your file name in the progress callback, currently it will only use the last value of i. Replace where you set your onprogress handler with this code.
(function(filename) {
xhr.upload.onprogress = function (e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
var progressbar = $('a[data-name="' + filename + '"]').siblings(".progress").find(".progress-bar");
progressbar.css("width", percentComplete + "%");
}
};
})(files[i].name);
You can do something like this. Set the additional parameters of xhr.upload
// Set custom properties
xhr.upload.targetFileName = fileName;
and then access it in progress handler like this
xhr.upload.onprogress = function (e) {
// Access custom properties.
var fileName = e.target.targetFileName;
}
More details here: https://hacks.mozilla.org/2009/06/xhr-progress-and-richer-file-uploading-feedback/ view-source:http://mozilla.pettay.fi/xhr_upload/xhr_file_upload_demo_with_speed.html

Backbone.js base64 video upload with progress bar

I have a script that sends a base64 video to the server via backbone/ajax:
video = new AccountVideo();
video.set({video: imageFile});
this.collection.create(video, {
// wait for return status from server
wait: true,
success: function(model, response) {
App.utils.notifyEnd('Video is queued for transcoding.');
accountVideoListView.render();
},
error: function(model, xhr) {
App.utils.notifyEnd(xhr.responseJSON.message, 'error');
}
});
I am trying to find away to create an upload progress bar similar to how this works, but within backbone entirely.
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "/api/accounts/videos");
ajax.send(imageFile);
function progressHandler(event){
var percent = (event.loaded / event.total) * 100;
console.log(percent);
} function completeHandler(event){
}
I tried:
var self = this;
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.onprogress = self.handleProgress;
return xhr;
}
handleProgress: function(evt){
var percentComplete = 0;
if (evt.lengthComputable) {
percentComplete = evt.loaded / evt.total;
}
console.log(Math.round(percentComplete * 100)+"%");
}
But it would only show a 0% after the video finished. I think I am close, just need a pointer. Thanks!
Ok, so I looked around and found out a little more about what's going on with the xhr: function.
Here is what is working
// add image model to collection
this.collection.create(video, {
// wait for return status from server
wait: true,
success: function(model, response) {
App.utils.notifyEnd('Video is queued for transcoding.');
accountVideoListView.render();
},
error: function(model, xhr) {
App.utils.notifyEnd(xhr.responseJSON.message, 'error');
},
xhr: function() {
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',showProgress, false);
} else {
console.log("Upload progress is not supported.");
}
return myXhr;
}
});
function showProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
console.log(percentComplete);
}
}

Categories

Resources