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>