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>
Related
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.
I cant find a way to get around my code. I have seen some tutorials out there, but because of the way I design my code I guess I need something different.
(function(){
var dropzone = document.getElementById('dropzone');
var uploadFile = function (files) {
var formData = new FormData();
var request = new XMLHttpRequest();
var i;
var file_size = 0;
for(i = 0; i<files.length; i = i+1){
formData.append('file[]', files[i]);
file_size = file_size + files[i].size;
}
request.onload = function(){
var data = this.responseText;
// window.location.reload();
};
request.open('post', 'dragNdrop.php?isNotSet=set');
request.send(formData);
};
dropzone.ondragover = function(){
this.className = 'dropzone dragover';
return false;
};
dropzone.ondragleave = function(){
this.className = 'dropzone';
return false;
};
dropzone.ondrop = function (event) {
event.preventDefault();
this.className = 'dropzone';
uploadFile(event.dataTransfer.files);
return false;
}
}());
This is the code I use to upload a file, but i cant find a way to add a eventlistener that keeps checking if the file has been uploaded. I have tried.
request.upload = function(){console.log("me")} //Returns nothing
I tried something like this:
request.upload.addEventListener("progress", progressBar, false);
function progressBar(event){
var percent = (event.loaded / event.total) * 100;
console.log(percent + " " + event.loaded + " " + event.total);
}
It only returns the value once, I would imagine it needs to return several times as it needs to loop in order to get the progress bar moving?
All this function below was inside the main function.
How else could I do this?
I have a js code which asks the user to input a code. I want to check if it is valid or it is programmed to say : code invalid! And if possible what happens when the code is valid.
Js Code:
myApp.prompt('Please enter your code, function (password) {
myApp.showPreloader('Checking Code...')
setTimeout(function () {
myApp.hidePreloader();
form.onsubmit = function(event) {
event.preventDefault();
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('bac.*')) {
continue;
}
formData.append('bac[]', file, file.name);
}
formData.append(name, file, filename);
formData.append(name, blob, filename);
formData.append(name, value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'bachandler.php', true);
xhr.onload = function () {
if (xhr.status === true) {
} else {
AlertBac();
}
};
}
xhr.send(formData);
}, 4000);
myApp.alert('code invalid ');
});
}, 5123)
}
},
]
})
});
You're missing the closing quote in the first line.
myApp.prompt('Please enter your code, function (password) {
should be
myApp.prompt('Please enter your code', function (password) {
I try to create simple "drag&drop" file upload. This my code:
HTML (index.html):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="script.js"></script>
<form action="upload.php">
<div id="dropZone">
Drag File
</div>
</form>
JavaScript (script.js):
$(document).ready(function() {
var dropZone = $('#dropZone'),
maxFileSize = 1000000;
dropZone[0].ondrop = function(event) {
event.preventDefault();
dropZone.removeClass('hover');
dropZone.addClass('drop');
var file = event.dataTransfer.files[0];
if (file.size > maxFileSize) {
dropZone.text('Max size 1mb!');
dropZone.addClass('error');
return false;
}
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', uploadProgress, false);
xhr.onreadystatechange = stateChange;
xhr.open('POST', 'upload.php');
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
alert(xhr.responseText);
};
function uploadProgress(event) {
var percent = parseInt(event.loaded / event.total * 100);
dropZone.text('Loading: ' + percent + '%');
}
function stateChange(event) {
if (event.target.readyState == 4) {
if (event.target.status == 200) {
dropZone.text('Ok!');
} else {
dropZone.text('Error!');
dropZone.addClass('error');
}
}
}
});
PHP (upload.php):
<?php
$uploaddir = 'upload/';
$uploadfile = $uploaddir.basename($_FILES['file']['name']);
if (!$_FILES)
{
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
}
?>
My problem is that file can't upload in folder, $_FILES['file']['tmp_name'] is empty...
Does anybody have an idea, where my mistake?
thank you...
Try this, Change your condition
if (isset($_FILES['file']))
{
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
}
How do I handle XMLHttpRequest data? I have a javascript/angular controller that takes some images and sends it to another page where I want to store the images to a database.
My code lokes like this:
modal.controller('UploadController', function ($scope) {
$scope.files = new Array();
$scope.getFiles = function (element){
$scope.$apply(function($scope){
for (var i = 0; i < element.files.length; i++) {
$scope.files.push(element.files[i])
}
console.log('files lenght : ' + $scope.files.length);
});
};
$scope.uploadFile = function () {
var data = new FormData();
var xhr = new XMLHttpRequest();
for(var i in $scope.files){
data.append("uploadedFile", $scope.files[i])
}
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", "fileupload.html")
$scope.progressVisible = true
xhr.send(data);
}
function uploadProgress(evt) {
$scope.$apply(function(){
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
} else {
$scope.progress = 'unable to compute';
}
})
}
function uploadComplete(evt) {
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
};
function uploadCanceled(evt) {
$scope.$apply(function(){
scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
};
});
In the the response text from the alert I get to see the html code from fileupload.html.
How can I recieve the data in fileupload.html so I can store the images in a database?