Use "Event" with another parameter - javascript

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"; }

Related

Javascript progress bar doesn't work with Firefox

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.

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

Blob data is not being sent to the PHP through XHR

I am trying to chunk a file and send to the server as follows
var fileselect = document.getElementById("file");
fileselect.addEventListener("change", FileSelectHandler, false);
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
}
function FileSelectHandler(e) {
FileDragHover(e);
var blob = e.target.files[0] || e.dataTransfer.files[0];
worker = new Worker("fileupload.js");
worker.postMessage(blob);
worker.onmessage = function(e) {
console.log(e);
};
}
fileupload.js
self.onmessage = function(e) {
const BYTES_PER_CHUNK = 1024 * 1024 * 32;
var blob = new Blob([e.data]),
start = 0,
index = 0,
slices = Math.ceil(blob.size / BYTES_PER_CHUNK),
slices2 = slices;
while (start < blob.size) {
end = start + BYTES_PER_CHUNK;
if (end > blob.size) end = blob.size;
uploadChunk(blob, index, start, end, slices, slices2);
start = end;
index++;
}
};
function uploadChunk(blob, index, start, end, slices, slices2) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
slices--;
if (slices == 0) {
var xhrMerge = new XMLHttpRequest();
xhrMerge.open("POST", "uploadlargefile/?a=merge&name=" + blob.name + "&slices=" + slices2);
xhrMerge.onload = function() {
self.close();
};
xhrMerge.send();
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) self.postMessage(Math.round(100 / e.total * e.loaded)); //this doesn't work o.O
};
var chunk = blob.slice(start, end);
xhr.open("POST", "uploadlargefile/?a=chunk&name=" + blob.name + "&index=" + index);
xhr.setRequestHeader("Content-Type", "multipart\/form-data; boundary=--------------------");
xhr.send(chunk);
}
PHP
print_r($_GET['name']); print_r($_FILES);die;
I am able to get the name of the file but not the file . Any suggestion what could be wrong

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

Categories

Resources