Skip to content
Advertisement

page of FLASK app is not changing after uploading a file, progress bar works fine

I want to perform some analysis on a text file. Once file is uploaded in the webpage, I am trying to redirect the route, But that isn’t working. Surprisingly, print statement is running in the console of the redirected route, but the template isn’t rendering.

Debug mode is true, I have multiple times ran this command set FLASK_DEBUG=1. I desperately need help :( Any help will be really appreciated.

imo there is some issue in javascript, which is not letting python change url.

My front end page is

<body>
    <div class="split left" >
        
        <img src="/static/acgt.png" class="logo"/>
        
        <h2><u>Description<br/><br/></u></h2>
        
        <p>There are some text in here</p>
        <br/>
        <br/>
        
        <div class="file-upload">
            <input class="file-upload__input" type="file" name="myFile" id="myFile" oninput="upload('{{ request.url }}');">
            <button class="file-upload__button" type="button" >Upload FASTA file from your device</button>
            <span class="file-upload__label"></span>
            
        </div>
        
        <div id="progress_wrapper" class="d-none">
            <label id="progress_status" style="color: white;">50% uploaded</label>
            <div class="progress mb-3">
                <div id="progress" class="progress-bar progress-bar-striped bg-info" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
            </div>
        </div> 

        <div >
            <p class = "errorMsg" style="margin-top: 20px; color:#FF6347 ; font-size:1.3em;">{{errorMessage}}</p>
        </div>
        
    </div>
    
    <div class="split right">
        
    </div>
    
    <script>
        
        const btn = document.querySelector('.file-upload__button')
        const hiddenInput = btn.parentElement.querySelector('.file-upload__input');
        const label = btn.parentElement.querySelector('.file-upload__label');
        const defaultLabelText = '';
        
        label.textContent = defaultLabelText;
        label.title = defaultLabelText;
        
        
        btn.addEventListener('click', function ( ) {
            hiddenInput.click();
        });
        
        hiddenInput.addEventListener('change',function() {
            const filename = Array.prototype.map.call(hiddenInput.files, function (file) {
                return file.name;
            });
            label.textContent = filename || defaultLabelText;  
        });  
        
        
        function upload(url) {
            
            var progress_wrapper = document.getElementById("progress_wrapper");
            
            progress_wrapper.classList.remove("d-none");
            
            var progress = document.getElementById("progress");
            
            var progress_status = document.getElementById("progress_status");
            
            var data = new FormData();
            
            var request = new XMLHttpRequest();
            
            request.responseType = "json";
            
            var file = hiddenInput.files[0];
            console.log(typeof(file));
            
            var filename = file.name;
            console.log(filename)
            var filesize = file.size;
            document.cookie = `filesize=${filesize}`;
            
            data.append("file", file);
            
            request.upload.addEventListener("progress", function (e) {
                
                // Get the loaded amount and total filesize (bytes)
                var loaded = e.loaded;
                var total = e.total
                
                // Calculate percent uploaded
                var percent_complete = (loaded / total) * 100;
                
                // Update the progress text and progress bar
                progress.setAttribute("style", `width: ${Math.floor(percent_complete)}%`);
                progress_status.innerText = `${Math.floor(percent_complete)}% uploaded`;
                
            });

            request.addEventListener("loadend",function(e){
                if(request.status == 200) {
                    console.log("Success should be shown using alert")
                    
                }else{
                    console.log("Failed to upload the file, Sad life :(")
                }
            });

            request.open("post", url);
            request.send(data);
        }
        
    </script>
    
</body>

and python page is

@app.route('/home', methods=["GET", "POST"])
def hello_world():
    if request.method == "POST":

        filesize = request.cookies.get("filesize")
        file = request.files["file"]
        res = make_response(jsonify({"message" : f"{file.filename} uploaded"}), 200)
        return redirect(url_for('dummyroute'))

    return render_template('home.html')

@app.route('/dummyroute')
def dummyroute():
    print("This is getting printed in console")
    return '<h1>I am getting mad<h1>' 

Advertisement

Answer

If you use JavaScript/AJAX to send request then response is send to this JavaScript code – and JavaScript’s request is redirected to /dummyroute and JavaScript gets response from /dummyroute but browser will not try to use this response to redirect full page.

AJAX was invented to NOT reload full page and browser doesn’t reload/redirect page when you use AJAX.

You will have do redirect full page directly in JavaScript – document.location = '/dummyroute'

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement