Home > Enterprise >  Send File using ajax jquery and read it at back end using Flask
Send File using ajax jquery and read it at back end using Flask

Time:01-27

I am trying to send a file using ajax jquery from the front end.

HTML

<label>Upload File </label>
<form method='post' enctype="multipart/form-data">
    <input type='file' id='uploaded_file'>
    <button id="submit-file">Submit</submit>
</form>

JavaScript

<script>
    
    $(document).ready(function(){

        $("#submit-file").click(function(event){

            var form_data = new FormData();
            form_data.append("uploaded_File_Name","MyFile");
            form_data.append("file",$("#uploaded_file").prop('files')[0]);
            

            $.ajax({
                url:"/read_uploaded_file",
                type:"POST",
                contentType: false,
                cache: false,
                processData: false,
                data: form_data,
                success: function(data){
                    console.log("Successful data upload");
                },
                error: function(data){
                    console.log("Error !!");
                }

            });
        });
    });
</script>

In the back end, I am using flask to read the file.

@app.route('/read_uploaded_file',method=["GET","POST"])
def read_uploaded_file():
    uploaded_file = request.files['file']

I get an error message POST (URL) 405 (METHOD NOT ALLOWED), Am i doing something wrong here? How do i fix it?

CodePudding user response:

POST (URL) 405 (METHOD NOT ALLOWED) error is due to the Cross Origin Resource Sharing (CORS).

To solve this added CORS at the backed:

from flask_cors import CORS

app= Flask(__name__)
CORS(app)

CodePudding user response:

In your .py file, it's not method=["GET","POST"], it is methods=["GET","POST"]. Try if it works, after changing that.

@app.route('/read_uploaded_file',methods=["GET","POST"])
def read_uploaded_file():
    uploaded_file = request.files['file']
  •  Tags:  
  • Related