Bad request 400 when sending file to flask server by ajax

Viewed 17

I am trying to send a file by browser to flask server. But don't know the reason why my flask server return 400 bad request error.

enter image description here

I used ajax to send a file sendform.html

<!DOCTYPE html>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type=text/javascript src="{{url_for('static', filename='jQuery.js') }}"></script>

<script>
   
   function fn_submit(){
    var form = new FormData();
   form.append("file1",$("#file1")[0].files[0]);
   jQuery.ajax({
    url : "http:127.0.0.1/request",
    type : "POST",
    processData : false,
    contentType : false,
    data : form,
    success:function(response){
        alert("success");
        console.log(response);
    },
    error: function(jqXHR){
        alert(jqXHR.responseText);
    }
   });
   }


</script>


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <label for="file1">파일</label> 
        <input type="file" id="file1" name="file1"> 
        <button id="btn_submit" onclick="javascript:fn_submit()">전송</button>    
    </div>
</body>
</html>

flaskServer.py

from flask import Flask, request, jsonify, Blueprint
from flask_wtf.csrf import CSRFProtect
from werkzeug.utils import secure_filename
import os
SECRET_KEY = os.urandom(32)

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

@app.route('/request', methods =['POST'])
def query():
    f = request.files['file']
    print('f ok')
    f.save('C:/Users/Tonykrjhc/Desktop/' + secure_filename('dasd.png'))
    return 'done!'

app.run(host="192.168.35.17",port=8227)

cannot solve this problem. and cannot found out specific reason why it makes 400 error. How to makes it work properly?

0 Answers
Related