简体   繁体   English

如何将音频文件从 express(node js)服务器发送到 Flask 服务器?

[英]How to send audio file from express(node js) server to flask server?

I uploaded a audio file(ex> wav) at frontend( react) , and succeed sending this file to backend(express / nodejs).我在前端(react)上传了一个音频文件(ex> wav),并成功将此文件发送到后端(express / nodejs)。

this is my frontend code (App.js)这是我的前端代码(App.js)

import React, { useRef, useEffect , useState } from 'react'
import VexFlow from 'vexflow'
import './App.css'
import axios from "axios";
import { Piano } from './components/Piano.js';
import { MIDINOTE } from './global/midinote';

const VF = VexFlow.Flow
const { Formatter, Renderer, Stave, StaveNote } = VF

const clefAndTimeWidth = 60        

export default function App() 
{
  const container = useRef() 
  const rendererRef = useRef()

  let clef = 'treble';
  let timeSignature = '2/4';
  let width = 450;
  let height = 150;

  const [check, setcheck] = useState(0);
  const countUp = ()=>{
    console.log('in countUp' + check);
    setcheck(check+1);
  }

  const [staves, setStaves] = useState([])
  async function getNoteData(){ //get data from Node JS server using axios
    await axios.get("http://172.10.18.168:80/aaa")
    .then((res)=>{
     
    })
    
    axios.get("http://172.10.18.168:80/data/")
    .then((res)=>{
      
      var lists =[]
      for(var i=0;i<Object.keys(res.data).length ; i++){
        var notes = MIDINOTE[res.data['note'+String(i)]['code']]
        //console.log(notes);
        lists.push(notes)
      }
      //staves = lists;
      setStaves([lists])
    });
    console.log(staves)
  }

  useEffect(() => {
    if (rendererRef.current == null) {
      rendererRef.current = new Renderer(
        container.current,
        Renderer.Backends.SVG
      )
    }
    const renderer = rendererRef.current
    renderer.resize(width, height)
    const context = renderer.getContext()
    context.setFont('Arial', 10, '').setBackgroundFillStyle('#eed')
    const staveWidth = (width - clefAndTimeWidth) / staves.length

    let currX = 0
    
    staves.forEach((notes, i) => {
      const stave = new Stave(currX, 0, staveWidth)
      if (i === 0) {
        stave.setWidth(staveWidth + clefAndTimeWidth)
        stave.addClef(clef).addTimeSignature(timeSignature)
      }
      currX += stave.getWidth()
      stave.setContext(context).draw()

      const processedNotes = notes
        .map(note => (typeof note === 'string' ? { key: note } : note))
        .map(note =>
          Array.isArray(note) ? { key: note[0], duration: note[1] } : note
        )
        .map(({ key, ...rest }) =>
          typeof key === 'string'
            ? {
                key: key.includes('/') ? key : `${key[0]}/${key.slice(1)}`,
                ...rest,
              }
            : rest
        )
        .map(
          ({ key, keys, duration = 'q' }) =>
            new StaveNote({
              keys: key ? [key] : keys,
              duration: String(duration),
            })
        )
      Formatter.FormatAndDraw(context, stave, processedNotes, {
        auto_beam: true,
      })
    })
  }, [check,staves])

  const [file,setFile] = useState();
  const [fileName,setFileName] = useState("");

  const saveFile = (e)=>{
    setFile(e.target.files[0]);
    setFileName(e.target.files[0].name);
  };
  const uploadFile = async(e)=>{
    const formData = new FormData();
    formData.append("file" ,file);
    formData.append("fileName" , fileName);
    try{
      const res = await axios.post(
        "http://172.10.18.168:80/upload",
        formData
      );
      console.log(res);
    }catch(ex){
      console.log(ex);
    }
  };

  return (
    <div className="App">
      <div ref={container} />
      <input type="file" onChange ={saveFile}/>
      <button onClick={uploadFile}>Upload</button>
      <button onClick ={countUp} >show music sheet</button>
      <button onClick ={getNoteData} >update music</button>
      <header className="App-header">
        <Piano/>
      </header>
    </div>
  ) 
}

At backend, I received this file and saved at my project directory.在后端,我收到了这个文件并保存在我的项目目录中。 this is my backend code.这是我的后端代码。 (app.js) (app.js)

import express, { response } from "express";      
const router = express.Router();
import cors from 'cors';
const app = express();
const port = 80;
import path from 'path'
const __dirname = path.resolve();
import aa from "./testAPI.js";
import { notedata } from "./testAPI.js"; // data from testAPI.js
import fileupload from 'express-fileupload'
import axios from "axios"; 

app.use(cors());
app.use(fileupload());
app.use(express.static("files"));

app.post('/upload' , (req,res)=> {
    console.log('file arrives at backend')

    const newpath = __dirname + "/files"; 
    const file = req.files.file; 
    const filename = file.name;   
    //console.log(__dirname); 

    file.mv(`${newpath}/${filename}`, (err)=>{
        if(err){
            console.log('failed!!')
        }
    });
    
});

app.get('/aaa', (req,res) => {
    aa.getTest();
    res.send('getTest /aaa') 
});

app.get('/bbb', (req,res) => {
    aa.postTest();
    res.send('postTest /bbb')
});

app.get('/data' , (req,res)=>{
    res.json(notedata); 
    console.log('node js ')
    console.log(notedata);
})

app.listen(port, (res) => {
    console.log("connecting");
})

I want to know how to send this received file to flask server.我想知道如何将此收到的文件发送到烧瓶服务器。 This is my flask code这是我的烧瓶代码

from flask import Flask, jsonify, request
from flask_restx import Resource, Api, reqparse
import main

app = Flask(__name__)
api = Api(app)
app.config['DEBUG'] = True


@app.route('/ddd')
def index():
    return 'Hello world'


@api.route('/test')
class testAPI(Resource):
    def get(self):

        notes = main.get_notes()
        data = {}
        i = 0
        for n in notes:
            tmp = {
                'second': n[0],
                'code': n[1]
            }
            data['note' + str(i)] = tmp
            i = i + 1

        data = jsonify(data)
        return data

    def post(self):

        parsed_request = request.files.get('content')
        notes = main.post_notes(parsed_request)
        data = {}
        i = 0
        for n in notes:
            tmp = {
                'second': n[0],
                'code': n[1]
            }
            data['note' + str(i)] = tmp
            i = i + 1

        data = jsonify(data)
        return data


if __name__ == '__main__':
    app.run(host="0.0.0.0", port="5000",  debug=True)

It is the same as sending a file from your React app to the Express server.这与从 React 应用程序向 Express 服务器发送文件相同。 (Just use FormData) (只需使用 FormData)

First, create a endpoint in your Flask server to receive the file.首先,在 Flask 服务器中创建一个端点来接收文件。

@app.route('/upload_express_to_flask', methods=['POST'])
    def upload_express_to_flask():
        file = request.form['file']
        file_name = request.form['fileName']

        // do something with the received file

Then, use axios in your Express server to send the file to your Flask server.然后,在 Express 服务器中使用 axios 将文件发送到 Flask 服务器。 In this case, your Express server acts as a client.在这种情况下,您的 Express 服务器充当客户端。

The code below is very simillar from your React app's uploadFile function.下面的代码与你的 React 应用程序的uploadFile函数非常相似。

I have added it to your existing /upload endpoint.我已将其添加到您现有的/upload端点。 This will send the file to the Flask server as soon as it receives the file from your React app.一旦它从您的 React 应用程序接收到文件,这就会将文件发送到 Flask 服务器。

app.post('/upload', async (req, res) => {
    
    // existing code for receiving the file

    const formData = new FormData();
    formData.append('file', file);
    formData.append('fileName', fileName);

    try {

        const res = await axios.post(
            'http://FLASK SERVER URL/upload_express_to_flask',
            formData
        );

        console.log(res);

    } catch(e) {

        console.log(e);

    }
    
});

Also, to use FormData in a Node.js app (Different from React because it is not running on a browser), you should use the form-data package.此外,要在 Node.js 应用程序中使用 FormData(与 React 不同,因为它不在浏览器上运行),您应该使用form-data包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将实时文件更新从Node JS Server(Express)发送到Angle JS - How to send realtime file update from node js server (express) to angular js 将文件从移动设备发送到Node js服务器 - Send a file from mobile to Node js server 从express node.js向其他服务器发送请求 - send request to other server from express node.js 如何从js文件向节点服务器发送代码? - how to send code to node server from js file? 如何从node.js服务器发送javascript缓冲区作为文件 - How to send javascript buffer as a file from node.js server 如何使用来自node.js(快速服务器)的服务器中的数据重写JS文件? - How can re-write JS file with data coming from server with node.js (express server)? 如何使用 Node.js express 从服务器向客户端发送实时 stream 响应 - How to send real time stream response from server to client using Node.js express 如何使用 Pusher 将用户的存款和取款详细信息从客户端发送到 Node.js(快递)服务器? - How to send deposit and withdraw details of user from client to Node.js (express) server using Pusher? 如何隐藏URL中的内容但仍然需要在node.js中发送到服务器并表达。 - How to hide content from URL but still need to send to server in node.js and express.? 如何使用 Node.js express 从服务器向客户端发送实时响应 - How to send real time response from server to client using Node.js express
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM