Maurio
Maurio

Reputation: 192

Implementing File Uploads From Angular to Flask

I am trying to implement file uploading for my Web tool. The front end is developed using angular and the back end is using flask. Following tutorials on the flask website I have set up the following flask app:

from flask import Flask, request
from werkzeug import secure_filename
import os

UPLOAD_FOLDER = '/home/openstack/Documents/Confmrg/bcknd/uploads'

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/uploader' , methods = ['GET' , 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'File Uploaded'


if __name__ == '__main__':
    app.run(debug = True)

I run this and the web server is hosted on http://localhost:5000

So on my angular component html I place the following:

<form action="http://localhost:5000/uploader" method="POST" enctype = "multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>

However when I run the angular web page, and test it by uploading a file and clicking submit, nothing happens. There is no error, and nothing is output in the console. I must be missing something, could someone point me in the right direction?

Upvotes: 3

Views: 4386

Answers (1)

ulmas
ulmas

Reputation: 2253

Form onSubmit handler

To answer your immediate question, what's happening is input type submit in Angular calls the onSubmit method of the form (instead of submitting the form like in plain HTML). And because you don't have a handler for onSubmit in your class, nothing is happening.

For a quick test, follow this link to create a simple onSubmit handler method to test that your submit button works.

Here's a Stackblitz example which logs to console when you click the submit button: https://stackblitz.com/edit/angular-uy481f

File upload

To make file upload work, you would need to make a few things. This touches the component class, creating a new service and injecting it, and updating your form to bind it to the class.

  1. Create a proper Angular form. Here's an example.
  2. Create a method that will handle the onSubmit() of the form.
  3. Create a service that will handle Http calls to upload files.
  4. Inject the service into your class, and call the file upload method of that class.

As you can see, there's a lot involved in making this work unlike having a simple post form in the template. As such, it will be too much for a single answer.

But hopefully, the initial paragraph answered your question and the rest of the answer pointed you in the right direction.

Upvotes: 2

Related Questions