Danielakaws
Danielakaws

Reputation: 47

Open a text file with XMLHttpRequest() using ajax in Flask Python

I am trying to use a very simple ajax example from W3school in Flask with Python. The example only loads some data from a file named ajax_info.txt to a page when a button is pressed. My desktop program has the next simplified structure:

FlaskProject
   app.py
   -uploads
      ajax_info.txt
   -templates
      html templates

I have uploaded the ajax_info.txt file to the server with the next code.

def uploader_func():
   
   if request.method == 'POST':
      f = request.files['file']
      file_path = os.path.join(app_config[UPLOAD_FOLDER], secure_filename(f.filename))
    
      f.save(file_path)
      #print(current_app.root_path)
      #print(os.path.isfile(os.path.join(app_config.UPLOAD_FOLDER, secure_filename(f.filename))))
      return 'file uploaded successfully'

This function successfully uploads the file and shows where it was uploaded locally, also I can see it in the uploads folder. Now I have to open it with the next script:

<!DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>

<p id="demo">Let AJAX change this text.</p>

<button type="button" onclick="loadDoc()">Change Content</button>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    console.log("hi");
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
      
    }
  };
  xhttp.open("GET", "uploads/ajax_info.txt", true);
  xhttp.send();
}
</script>

</body>
</html>

I have tried all possible combinations of the URL to access the file in the xhttp.open () function but none works. I get the error net::ERR_ABORTED 404 (NOT FOUND)

I have tried:

I am confused about how should I access this file. Any kind of help will be appreciated

Upvotes: 0

Views: 802

Answers (1)

bas
bas

Reputation: 15442

You could create a static folder and put the upload folder inside.

static_folder (Optional[str]) – The folder with static files that is served at static_url_path. Relative to the application root_path or an absolute path. Defaults to 'static'.

https://flask.palletsprojects.com/en/2.0.x/api/

Then you can do this in your Javascript code:

xhttp.open("GET", "static/uploads/ajax_info.txt", true);

Upvotes: 1

Related Questions