Javascript automatic file input fill and upload - javascript

I have json file genertor and file upload input on my page and its working like that:
Press button "Generate file" then press link "Download" then save file "test.json" locally.
Then I can load this file and send to target using html input file on the same page.
But I dont know how to upload generated file automaticaly using "doSubmit" function when button "Generate file" is pressed without saving locally before.
Is it even possible?
Can someone help how to solve this problem?
I am still beginner and I cant help myself...
Thank you very much!
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Generate Json File In JavaScript</title>
</head>
<body>
<div class="wrap-title">
<h2>Generate Json File using plain JavaScript</h2>
</div>
<div class="wrap-footer">
<button id="btnCreateFile">Generate File</button>
<a download="test.json" id="downloadFile" style="display: none">Download</a>
</div>
<hr>
<h5>File upload</h5>
<input class="form-control" type="file" id="file-select-input">
<div class="input-group-append">
<button class="btn btn-primary btn-sm" type="button" style="width: 120px" onclick='doSubmit()' id="upload-button" >Upload</button>
</div>
<hr>
<script>
var upData = "[\n";
function doJson(){
var num = 5;
for ( let i = 1; i < num + 1 ; i++ ){
upData += "{\"nr\":\"" + i + "\",\"class\":" + i + ",\"group\":" + i + "}";
if ( i < num ) upData += ",\n"; else upData += "\n]";
}
}
function generateJsonFile(text){
var jsonFile = null;
var data = new Blob([text], {type: 'text/json'});
if (jsonFile !== null) {
window.URL.revokeObjectURL(jsonFile);
}
jsonFile = window.URL.createObjectURL(data);
return jsonFile;
}
(function () {
btnCreateFile.addEventListener('click', function () {
var link = document.getElementById('downloadFile');
doJson();
console.log( upData );
link.href = generateJsonFile(upData);
link.style.display = 'inline-block';
}, false);
})();
function doSubmit(){
var formData = new FormData();
var fileSelect = document.getElementById( "file-select-input" );
if( !fileSelect.files[0] ) return; /* do not send empty file input */
document.getElementById( "upload-button" ).innerHTML = 'Uploading...';
if( fileSelect.files && fileSelect.files.length == 1 ) {
var file = fileSelect.files[0]
formData.append( "fileUpload", file , file.name );
}
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){ /* prepare response */
if( ajaxRequest.readyState == 4 && ajaxRequest.status == 200 ){
if( ajaxRequest.responseText == "ERROR" ) document.getElementById( "upload-button" ).innerHTML = 'Error';
else if( ajaxRequest.responseText == "OK" ) {
document.getElementById( "upload-button" ).innerHTML = 'Upload'; /* change upload button label */
document.getElementById( "file-select-input" ).value = null; /* empty file input -> prevent send the same data again */
console.log( 'file delivered OK!');
}
}
}
ajaxRequest.open( 'POST', "fileUpload" );
ajaxRequest.send( formData );
console.log( "file sent..." );
}
</script>
</body>
</html>

Related

uploading a file in chunks using html5 , javascript and PHP

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.

CSV not importing

I am trying to create a csv editor. I want to import a csv and convert it to tables in html. This is the following code:
<html>
<head>
<title></title>
</head>
<body>
<div class="container">
<h1>Build Table</h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file">
<div>
<table id="blacklistgrid">
<tr class="Row">
<td>
<input type="text"/>
</td>
<td>
<input type="text"/>
</td>
<td>
<input type="text"/>
</td>
</tr>
</table>
<button type="button" id="btnAdd">Add Row!</button>
<button>Export Table data into Excel</button>
</div>
<script>
function parseResult(result) {
var resultArray = [];
result.split("\n").forEach(function(row) {
var rowArray = [];
row.split(",").forEach(function(cell) {
rowArray.push(cell);
});
resultArray.push(rowArray);
});
return resultArray;
}
function createTable(array) {
var content = "";
array.forEach(function(row) {
content += "<tr>";
row.forEach(function(cell) {
content += "<td><input type=\"text\" value=\"" + cell + "\"/></td>" ;
});
content += "</tr>";
});
document.getElementById("#blacklistgrid").innerHTML = content;
}
jQuery(document).ready(function () {
jQuery('#btnAdd').click(function () {
jQuery( ".Row" ).clone().appendTo( "#blacklistgrid" );
});
var file = document.getElementById('file');
file.addEventListener('change', function() {
var reader = new FileReader();
var f = file.files[0];
reader.onload = function(e) {
var CSVARRAY = parseResult(e.target.result); //this is where the csv array will be
createTable(CSVARRAY);
};
reader.readAsText(f);
});
});
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function(i, row) {
var $row = $(row),
$cols = $row.find('input');
return $cols.map(function(j, col) {
var $col = $(col),
text = $col.val();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"';
// Deliberate 'false', see comment below
if (false && window.navigator.msSaveBlob) {
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});
// Crashes in IE 10, IE 11 and Microsoft Edge
// See MS Edge Issue #10396033
// Hence, the deliberate 'false'
// This is here just for completeness
// Remove the 'false' at your own risk
window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) {
// HTML5 Blob
var blob = new Blob([csv], {
type: 'text/csv;charset=utf-8'
});
var csvUrl = URL.createObjectURL(blob);
$(this)
.attr({
'download': filename,
'href': csvUrl
});
} else {
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
}
// This must be a hyperlink
$(".export").on('click', function(event) {
// CSV
var args = [$('#blacklistgrid'), 'export.csv'];
exportTableToCSV.apply(this, args);
// If CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
</script>
</body>
</html>
I cannot get the import function to work. And, these are the following errors:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at createTable ((index):54)
at FileReader.reader.onload ((index):69)
What am I doing wrong?
Don't put # in the argument to document.getElementById. It should be:
document.getElementById("blacklistgrid").innerHTML = content;
or using jQuery:
$("#blacklistgrid").html(content);

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>

Drop down box text disappears after completing a function, how can I get it to display what option was chosen?

The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}

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