0

I'm new to python flask, I'm using flask in backend and react js in front end and pymongo for the database. I want to upload the file from ReactJs to the flask server, I 'm getting an error while doing second method, How can I do it. Below is the code that I have tried.

I had tried two examples one is working and the other is not I don't know why.

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'file'

  1. Directly sending the file to API. Case 1

Python code

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set([ 'png', 'jpg', 'jpeg'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/api/users/add_photo', methods=['POST', "GET"])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            image = upload(open(filename, 'rb'))
            user_id = user.insert({"file":image})
            return jsonify({'result': "file Upload successfully!!!"})
onSubmitImage(e) {
    let file = this.state.file;
    let formData = new FormData();
    formData.append("file", file);
    this.props.imageUpload(formData);
  }

Above example is working perfectly

  1. Sending a file to API in the object. Case 2

Python code

import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = '/path/to/the/uploads'
ALLOWED_EXTENSIONS = set([ 'png', 'jpg', 'jpeg'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/api/users/add_photo', methods=['POST', "GET"])
def upload_file():
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        name = request.get_json(force=True)["name"]
        last_name = request.get_json(force=True)["last_name"]
        email = request.get_json(force=True)["email"]
        # if user does not select file, browser also
        # submit a empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            image = upload(open(filename, 'rb'))
            user_id = user.insert({"file":image,"name":name,"last_name":last_name,"email":email})
            return jsonify({'result': "file Upload successfully!!!"})

 onSubmitImage(e) {
    let file = this.state.file;
    let formData = new FormData();
    formData.append("file", file);
    const data = {
      file: formData
      name: this.state.name
      last_name: this.state.last_name
      email: this.state.last_name
    };
    this.props.imageUpload(data);
  }

I don't know why first is working and second not. I want to implement the second example because there other are data like name, last_name, email with image file.

2

365体育足球滚球比分You need to add your data to your FormData()- ie

let file = this.state.file;
let formData = new FormData();
formData.append("file", file);
formData.append("name", this.state.name);
formData.append("last_name", this.state.last_name)
formData.append("email", this.state.last_name)
this.props.imageUpload(formData);
| improve this answer | |
  • what if I want to upload multiple files with other data instead of a single file what code I have to change react as well as in python?? – chirag prajapati Apr 1 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy365体育足球滚球比分

Not the answer you're looking for? Browse other questions tagged or ask your own question.