uploading a file in chunks using html5 , javascript and PHP - javascript

Basically i have to upload file by chunks as the file is very big,i tried using this solution uploading a file in chunks using html5 but the file is corrupt because the file reconstructed is not in order.
I tried to implement the answer given in the link but i really confused how can i implement it on my php page and my html page. If you guys could give me an advice or a way of doing it, that would be great. Thank you for your time.
The code :
upload.php
<?php
$target_path = "/home/imagesdcard/www/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$target_file = $target_path . basename($name);
$complete = "test.txt";
$com = fopen("/home/imagesdcard/www/".$complete, "ab");
error_log($target_path);
// Open temp file
$out = fopen($target_file, "wb");
if ( $out ) {
// Read binary input stream and append it to temp file
$in = fopen($tmp_name, "rb");
if ( $in ) {
while ( $buff = fread( $in, 1024) ) {
fwrite($out, $buff);
fwrite($com, $buff);
}
}
fclose($in);
fclose($out);
}
fclose($com);
?>
html
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script type="text/javascript">
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
function sendRequest() {
var blob = document.getElementById('fileToUpload').files[0];
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
var i=0;
var start = 0;
var end = BYTES_PER_CHUNK;
while( start < SIZE ) {
var chunk = blob.slice(start, end);
uploadFile(chunk,i);
i++;
start = end;
end = start + BYTES_PER_CHUNK;
}
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile(blobFile,part) {
//var file = document.getElementById('fileToUpload').files[0];
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php?num="+part);
xhr.onload = function(e) {
alert("loaded!");
};
xhr.send(fd);
//alert("oen over");
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
//alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
<input type="button" value="cancel" onClick="uploadCanceled();"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="sendRequest();" value="Upload" />
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>

Your script doesn't work because js is async.
You should change your code to:
xhr.open("POST", "upload.php?num="+part, false);
and file save fine.
My solution for upload big files by chunk.
upload.php (php part)
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$chunk = $_FILES["chunk"]["tmp_name"];
$filename = $_POST['filename'];
if(!isset($_SESSION[$filename]))
{
$_SESSION[$filename] = tempnam(sys_get_temp_dir(), 'upl');
}
$tmpfile = $_SESSION[$filename];
if(isset($chunk))
{
file_put_contents($tmpfile, file_get_contents($chunk), FILE_APPEND);
}
else
{
rename($tmpfile, $filename);
}
exit();
}
?>
upload.php (html\js part)
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
function sendRequest() {
// 1MB chunk sizes.
var chunk_size = 1048570;
var file = document.getElementById('file').files[0];
var filesize = file.size;
var filename = file.name;
var pos = 0;
while(pos < filesize) {
let chunk = file.slice(pos, pos+chunk_size);
pos += chunk_size;
var data = new FormData();
data.append('chunk', chunk);
data.append('filename', filename);
$.ajax({url:'upload.php',type: 'post',async:false,data: data,processData: false,contentType: false});
let percentComplete = Math.round(pos * 100 / filesize);
document.getElementById('progressNumber').innerHTML = (percentComplete > 100 ? 100 : percentComplete) + '%';
}
$.post('upload.php',{filename:filename});
}
</script>
</head>
<body>
<form>
<div class="row">
<label for="file">Select a File to Upload</label><br />
<input type="file" name="file" id="file" onchange="sendRequest();"/>
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>
but this code have one bug - progress bar don't work in chrome because sync request used, work only in firefox.

Related

Upload multiple files parallel in azure blob with SAS Token in javascript

I am trying to upload multiple video files in azure blob storage with the help of SAS token.
As you can see in this image :- Image
By looking in the console It looks like browser is handling the file and uploading it by chunks. So I didn't implemented it in my code. Don't know if that's the right way.
Files are uploading successfully but its taking lot of time.
<div class="container">
<div class="row">
<div class="form-group">
<label for="Files"></label>
<input type="file" id="fileControl" multiple />
<br />
<span class="" id="SizeLimitSAS" style="visibility: hidden; font-size:small"></span>
<br />
<progress id="uploadProgress" class="form-control" value="0" max="100" style="height: 60px;"></progress>
<br />
</div>
<div class="form-group">
<input type="button" id="btnUpload" value="Upload files" />
</div>
<br />
<br />
<span class="" id="countOfFileUploaded" style="visibility: hidden; font-size:large"></span>
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#fileControl').addEventListener('change', handleFileSelect, false);
sizeLimit = document.querySelector("#SizeLimitSAS");
}
function handleFileSelect(e) {
if (!e.target.files) return;
var totalSize = 0;
sizeLimit.innerHTML = "";
var files = e.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
totalSize += f.size;
}
console.log(files)
console.log(totalSize)
sizeLimit.innerHTML += "</br>" + niceBytes(totalSize);
SizeLimitSAS.style.visibility = "visible";
}
const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
function niceBytes(x) {
let l = 0, n = parseInt(x, 10) || 0;
while (n >= 1024 && ++l) {
n = n / 1024;
}
return (n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}
var count = 0;
function upload(file, type, url) {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function (aEvt) {
console.log(ajaxRequest.readyState);
if (ajaxRequest.readyState == 4)
console.log(ajaxRequest.responseText);
};
ajaxRequest.upload.onprogress = function (e) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + "% completed");
if (percentComplete === 100) {
count++;
countOfFileUploaded.innerHTML = count + " file uploaded";
countOfFileUploaded.style.visibility = "visible";
}
uploadProgress.value = percentComplete;
};
ajaxRequest.onerror = function (jqXHR, exception, errorThrown) {
alert(jqXHR.status + "--" + exception + "--" + errorThrown);
};
ajaxRequest.open('PUT', url, true);
ajaxRequest.setRequestHeader('Content-Type', type);
ajaxRequest.setRequestHeader('x-ms-blob-type', 'BlockBlob');
ajaxRequest.send(file);
}
jQuery("#btnUpload").click(function () {
var files = fileControl.files;
for (var i = 0, file; file = files[i]; i++) {
upload(file, file.type, "https://container.blob.core.windows.net/videos/" + file.name + "?sp=racwdli&st=2023-01-18T12:51:14Z&se=2023-01-21T20:51:14Z&sv=2021-06-08&sr=c&sig=gfgkkbhbkekhbkigyyuvuuQB2XR1ynaSOQ%3D");
}
});
</script>
I tried in my environment and successfully uploaded file parallelly in Azure blob storage using browser.
You can use the below code to upload file parallely with SAS url:
Index.html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<button id="select-button">Select and upload files</button>
<input type="file" id="file-input" multiple style="display: none;" />
<div id="showProgress"></div>
<p><b>Status:</b></p>
<p id="status" style="height:300px; width: 593px; overflow: scroll;" />
</body>
<script type="module" src="index.js"></script>
</html>
Index.js
const { BlobServiceClient } = require("#azure/storage-blob");
const selectButton = document.getElementById("select-button");
const fileInput = document.getElementById("file-input");
const status = document.getElementById("status");
const reportStatus = message => {
status.innerHTML += `${message}<br/>`;
status.scrollTop = status.scrollHeight;
}
const blobSasUrl = "<blob sas url>";
const blobServiceClient = new BlobServiceClient(blobSasUrl);
const containerName = "test";
const containerClient = blobServiceClient.getContainerClient(containerName);
const uploadFiles = async () => {
try {
reportStatus("Uploading files...");
const promises = [];
for (var fileIndex = 0; fileIndex < fileInput.files.length; fileIndex++) {
const file = fileInput.files[fileIndex];
const blockBlobClient = containerClient.getBlockBlobClient(file.name);
document.getElementById('showProgress').innerHTML += file.name +":<div id='progress-"+ file.name +"'></div>"
var blobUploadOptions = {
blockSize: 4 * 1024 * 1024, // 4MB block size
parallelism: 20, // 20 concurrency
metadata: { 'testindex': fileIndex.toString() },
progress: function (ev) {
var percentdone = ((ev.loadedBytes / file.size) * 100);
var progessItem = document.getElementById('progress-' + file.name);
progessItem.innerHTML = percentdone.toFixed(2) + "%";
}
};
var promise=blockBlobClient.uploadBrowserData(file,blobUploadOptions);
promise.then((result)=>{
var progessItem = document.getElementById('progress-' + file.name);
progessItem.innerHTML += " file link"
});
promises.push(promise);
}
await Promise.all(promises);
alert("Done.");
}
catch (error) {
alert(error.message);
}
}
selectButton.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", uploadFiles);
Console:
Browser:
Portal:
Reference:
Quickstart: Azure Blob storage library v12 - JS Browser - Azure Storage | Microsoft Learn

Local file upload -> Canvas greyscale and downscale -> ocr.space

Hi all you fantastic people. I'm a bit of a newbie on this.
I want to local select a file -> greyscale and downscale it (because it offen comes from a mobile devices) -> And then upload it to the ocr.space
Here is what I have so far on downscale:
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width=800
canvas.height=600
ctx.drawImage(img, 0, 0, 800, 600);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
<html>
<head>
<title>Upload PNG, JPG file</title>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>
</body>
</html>
How do I send it to OCR with the following code so far:
(My OCR code takes file input, but I have a canvas because I need to downscale it first).
<?php
if(isset($_POST['submit']) && isset($_FILES)) {
require __DIR__ . '/vendor/autoload.php';
$target_dir = "uploads/";
$uploadOk = 1;
$FileType = strtolower(pathinfo($_FILES["attachment"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . generateRandomString() .'.'.$FileType;
// Check file size
if ($_FILES["attachment"]["size"] > 990000) {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, filen er desværre for stor";
$uploadOk = 0;
}
/*if($FileType != "png" && $FileType != "jpg") {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, det skal være en jpg, jpeg eller png fil";
$uploadOk = 0;
}*/
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file)) {
uploadToApi($target_file);
} else {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, der skete en fejl da foto blev uploadet.";
}
}
} else {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, venligst upload en fil";
}
function uploadToApi($target_file){
require __DIR__ . '/vendor/autoload.php';
$fileData = fopen($target_file, 'r');
$client = new \GuzzleHttp\Client();
try {
$r = $client->request('POST', 'https://api.ocr.space/parse/image',[
'headers' => ['apiKey' => 'xxxxxxxx'],
'multipart' => [
[
'name' => 'file',
'contents' => $fileData
]
]
], ['file' => $fileData]);
$response = json_decode($r->getBody(),true);
if($response['ErrorMessage'] == "") {
?>
<html>
<head>
<title>Result</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js'></script>
</head>
<body>
<div class="form-group container">
<label for="exampleTextarea">Result</label>
<input type="text" id="nummerplade" name="nummerplade" value="<?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?>">
<textarea class="form-control" id="exampleTextarea" rows="30"><?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?></textarea>
</div>
</body>
</html>
<?php
} else {
header('HTTP/1.0 400 Forbidden');
echo $response['ErrorMessage'];
}
} catch(Exception $err) {
header('HTTP/1.0 403 Forbidden');
echo $err->getMessage();
}
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
I'm writing this answer to clarify how to apply the information referenced in my previous comment. You won't use the $_FILES variable at all. You will instead post your canvas as a data url in a normal variable through ajax and you will access it through the $_POST variable. Then you will process this data url to get the binary image and do everuting you want with it, i.e. save it to a file, post it to ocr service, etc.
The following code on the client side uses jquery, you have to download it in the same dir or replace the src attribute with a public available url (CDN):
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script>
$(function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
canvas.width=80
canvas.height=60
ctx.drawImage(img, 0, 0, 80, 60);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$('#upload').click(function() {
var canvasData = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: canvasData
}
}).done(function(o) {
alert('Image sent to the server');
});
});
});
</script>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>
<button id="upload">Upload</button>
</body>
</html>
The php script should be like this:
<?php
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//... do anything you want with $fileData ...
?>

file.files[0] cannot read property '0' of undefined

Oddly enough if I use this code in a jsfiddle it works perfectly
var file = document.getElementById("file");
function CallAlert(){
alert(file.files[0].name);
}
<form method="post" enctype="multipart/form-data">
<div>
<label for="file">Choose file to upload</label>
<input type="file" id="file" name="file" onchange="CallAlert()">
</div>
<div>
<button>Submit</button>
</div>
</form>
The result of this is an alert with the name of the file
Now on to my issue using this same method in sorts in my case this returns Uncaught TypeError: Cannot read property '0' of undefined
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _('file1').files[0];
if (typeof file === 'undefined') {
_('status').innerHTML = 'ERROR: Please browse for a file before clicking the upload button';
_('progressBar').value = 0;
} else {
$.get('https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php?getsize', function(sizelimit) {
if (sizelimit > file.size) {
var formdata = new FormData();
formdata.append('file1', file);
formdata.append('size', file.size);
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', 'https://outsource.technologyforthefuture.org/wp-content/plugins/video-contest/shortcodes/handles/upload_handle.php');
ajax.send(formdata);
} else {
var sizewarn = 'ERROR: The File is too big! The maximum file size is ';
sizewarn += sizelimit / (1024 * 1024);
sizewarn += 'MB';
_('status').innerHTML = sizewarn;
_('progressBar').value = 0;
}
});
}
}
function progressHandler(event) {
// _('loaded_n_total_bytes').innerHTML = event.loaded+'bytes/''+event.total+'bytes';
// _('loaded_n_total_kb').innerHTML = event.loaded/1024+'kb/''+event.total/1024+'kb';
_('loaded_n_total_mb').innerHTML = Math.round(event.loaded / 1024 / 1024) + 'mb/' + Math.round(event.total / 1024 / 1024) + 'mb';
var percent = (event.loaded / event.total) * 100;
_('progressBar').value = Math.round(percent);
_('percentage_loaded').innerHTML = Math.round(percent) + '%';
if (Math.round(percent) == 100) {
_('status').innerHTML = 'Generating Link Please Wait...';
} else {
_('status').innerHTML = 'uploading... please wait';
}
}
function completeHandler(event) {
_('status').innerHTML = event.target.responseText;
_('progressBar').value = 0;
}
function errorHandler(event) {
_('status').innerHTML = 'Upload Failed';
}
function abortHandler(event) {
_('status').innerHTML = 'Upload Aborted';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1" onchange="uploadFile()"><br>
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<p class="loading">
<pt id="percentage_loaded"></pt>|
<!--<pt id="loaded_n_total_bytes"></pt>|
<pt id="loaded_n_total_kb"></pt>|-->
<pt id="loaded_n_total_mb"></pt>|
<pt id="status"></pt>
</p>
</form>
What I am trying to do is when a file is selected it sends it as an ajax response to a script to put the file on our server. I dont see how this is producing an error when there is no difference in the example snippet vs my actual code other then the extra stuff around it but I dont see how that could be affecting it.
Perhaps someone smarter then me knows what the answer to this issue is.
instead of this
function uploadFile() {
var file = _('file1').files[0];
...
try this
function uploadFile(event){
var file=event.target.files[0];
...
and don't forget to change this
<input type="file" name="file1" id="file1" onchange="(event)=>uploadFile(event)"><br>

Php is not working with ajax

html code
<form method="post" name="file_upload" enctype="multipart/form-data" id="file_upload">
<input type="file" id="_file" name="_file"> <br>
<input type="button" id="button" value="upload"/> <br>
<progress id="p_bar" value="0" max="100" style="width:300px;"> </progress>
</form>
<p id="status"> </p>
<script src="final.js" > </script>
js
var sfile = document.getElementById('_file') ;
var btn = document.getElementById('button') ;
var f_upload= document.getElementById('file_upload') ;
var pbar = document.getElementById('p_bar') ;
var sbar = document.getElementById('status') ;
function upload () {
if(sfile.files.length==0) {
alert("files isn't select ") ;
}
var s_file = sfile.files[0] ;
var formdata = new FormData () ;
formdata.append( 'selected file ',s_file) ;
var ajax = new XMLHttpRequest () ;
ajax.upload.addEventListener("progress", progress , false ) ;
function progress (event) {
var percent = (event.loaded / event.total) * 100 ;
pbar.value = Math.round(percent) ;
sbar.innerHTML = Math.round(percent)+"%.........uploaded" ;
}
ajax.open("POST", "final.php") ;
ajax.send(formdata) ;
}
btn.addEventListener("click", upload , false ) ;`
PHP
<?php
$file_name = $_FILES['_file']['name'] ;
$file_temp = $_FILES['_file']['tmp_name'] ;
$file_size = $_FILES['_file']['size'] ;
$file_type = $_FILES['_file']['type'] ;
$file_error = $_FILES['_file']['size'] ;
$file_destination = "upload/".basename($file_name) ;
if( move_uploaded_file($file_temp, $file_destination) ) {
echo "file uploaded" ;
}
else {
echo " file is failed to upload " ;
}
In these no working on php . if i only put echo still not output in main page . also if in php we caught with name tag in html than why use of send function in ajax.like ajax.send(formdata)
the problem here is you are not looking for ajax response.try this:
<script>
var sfile = document.getElementById('_file');
var btn = document.getElementById('button');
var f_upload= document.getElementById('file_upload');
var pbar = document.getElementById('p_bar');
var sbar = document.getElementById('status');
var ajax = null;
function upload () {
if(sfile.files.length==0) {
alert("files isn't select ");
return;
}
var s_file = sfile.files[0];
var formdata = new FormData();
formdata.append('_file',s_file);//your key is _file
ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progress , false);
ajax.open("POST", "final.php");
ajax.onreadystatechange = OnStateChange;
ajax.send(formdata);
}
btn.addEventListener("click", upload , false);
function progress (event) {
var percent = (event.loaded / event.total) * 100;
pbar.value = Math.round(percent);
sbar.innerHTML = Math.round(percent)+"%.........uploaded";
}
function OnStateChange () {
if (ajax.readyState == 4 && ajax.status == 200) {
var resp = ajax.responseText;
alert(resp);
}
}
</script>

stop javascript to redirect after alert() function

I am using javascript to check file size. If it is bigger than 1m it shows an alert and after that it redirect to index page.
I want know how to make it stay in the same page without redirect and without refresh and keep all page information inserted by user as it is.
This is the code:
if(fileInput.files[0].size > 1050000) {
alert('File size is bigger than 1Mb!');
return false;
}
the hole code:
var handleUpload = function(event){
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('javascript', true);
if(fileInput.files[0].size > 1050000) {
//document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)";
alert('File bigger than 1Mb!');
//window.location="upload.php";
return false;
}
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if(event.lengthComputable){
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while (progress.hasChildNodes()){
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +' %'));
document.getElementById("loading-progress-17").style.width= Math.round(percent * 100) +'%';
}
});
request.upload.addEventListener('load', function(event){
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event){
alert('Upload failed');
});
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if(this.status == 200){
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
}else{
console.log('server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load', function(event){
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
the upload.php code with the html
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['javascript'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
Thanks in advance
You may get rid of return it should work. Else, maybe you should try modals instead of alerts. They are more neat and pretty
Return false is preventing the redirect.
var val = $("#inputId").val();
if (val >= 0 || val <=9)
{
return true;
}
else
{
alert("Enter Digits Only");
return false;
}
```
Add event.preventDefault(); below the alert function.
This may help you to stay on the same page.

Categories

Resources