0

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> 
motoma
  • 31
  • 5
  • The "upload file" will likely require an `` - but since you generated it, do you need to save as a file? Is there a design constraint such as file size or otherwise driving that? – Mark Schultheiss Apr 26 '21 at 14:25
  • This is just an example but generated json file size can be 0 - 100kb. – motoma Apr 26 '21 at 16:11
  • I forgot to say that code runs on ESP32 cpu, where server argument has limited size about 2kb, but has implemented !file upload routine for bigger files.So this is reason why I need use "doSubmit" function and send data as file.Another way is divide generted file to smaller pieces, but I would like send it as one file... – motoma Apr 27 '21 at 04:26
  • https://stackoverflow.com/q/20611677/125981 and https://stackoverflow.com/a/133997/125981 seem like the same action you have here – Mark Schultheiss Apr 27 '21 at 14:05
  • Does this answer your question? [JavaScript post request like a form submit](https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit) – Mark Schultheiss Apr 27 '21 at 14:05
  • Thanj you. No, I still dont know how to fill file input with just generated jsom file. – motoma Apr 27 '21 at 16:01
  • At this moment I solved this problem by dividing generated json file to smaller pieces and send one by one using XMLHttpRequest. – motoma Apr 27 '21 at 19:15

0 Answers0