Carl Smestad
Carl Smestad

Reputation: 219

Sending .wav file from React frontend to Flask backend

I am quite new new Flask and Blobs in general, but I've been trying for some time to send a .wav file from my frontend to my backend. In general it seems like I should put the file into a FormData(), and send a post-request to the backend.

Here is my frontend code:

import React from "react";
import { DropzoneArea } from "material-ui-dropzone";
import axios from "axios";

const DropzoneAreaExample = () => {
  const headers = {
    "content-type": "multipart/form-data",
  };

  const fileDrop = (files: File[]) => {
    const formData = new FormData();

    const file: File = files[0];
    formData.append("file", file);

    axios
      .post("http://localhost:5000/analyze", { formData }, { headers })
      .then((res) => console.log(res.data));
  };

  return (
    <div>
      <DropzoneArea onDrop={fileDrop} />
    </div>
  );
};

export default DropzoneAreaExample;

And on the backend I am trying this:

import flask
from flask import request
from flask_cors import CORS

app = flask.Flask(__name__)
CORS(app)


@app.route('/analyze', methods=['GET', 'POST'])
def analyze_data():
    if request.method == 'POST':
        f = request.files['file']
        f.save()
        return "test"

Any help or nudge in the right direction would be much appreciated!

Upvotes: 1

Views: 1248

Answers (2)

Musa
Musa

Reputation: 97672

When you pass the data to Axios post as the second parameter, you do not put it in an object.

axios
  .post("http://localhost:5000/analyze", formData, { headers })
  .then((res) => console.log(res.data));

Upvotes: 1

Carl Smestad
Carl Smestad

Reputation: 219

I finally found a solution. The problem was in the axios-request. I transformed it to a fetch-request, and then everything worked out. Here's the working request from the frontend:

const FileUploader = () => {
  const fileDrop = (files: File[]) => {
    const formData = new FormData();

    const file: File = files[0];
    formData.append("file", file);

    fetch("http://localhost:5000/upload", {
      method: "POST",
      body: formData,
    }).then((res) => {
      console.log(res.text);
    });
  };

Upvotes: 0

Related Questions