相当于axios(nodejs)中的curl命令用于文件上传?

Equivalent to curl command in axios (nodejs) for file upload?

我有以下命令可用于上传 .wav 文件

curl  http://127.0.0.1:5000/upload -F file=@./1653671203458audio.wav

服务器端相关代码如下,使用Flask

@app.route('/upload', methods=['POST', 'PUT'])
def upload_file():
    if request.method == 'POST' or request.method == 'PUT':
        print(request.files)
        #print(request.args)
        #print(request.form)
        #print(request.files["onlyFile"])
        if 'file' not in request.files:
            return "no file was sent"
        file = request.files['file']
        print(file.filename)
        if file.filename == '':
            return "No  selected file"
        #if file in allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
        return "File was uploaded successfully"

我已经尝试了很多尝试并尝试在 nodejs 中以相同的方式上传它但没有成功,以下是最新的并且它 returns“没有文件被发送”

const axios = require("axios");
const fs = require("fs");
const FormData = require('form-data');

var fData = new FormData()
selectedFile = fs.readFileSync("./1653671203458audio.wav")

fData.append("1653671203458audio.wav", Buffer.from(selectedFile));
axios.post("http://127.0.0.1:5000/upload", {
  fData, 
  headers: fData.getHeaders()
}).then(function (response) {
  console.log(response.data);
}).catch(function(response){
  console.log(response);
});

检查axios example

所以 file=@./1653671203458audio.wav 应该是 fData.append("file", selectedFile); 另外,axios post 参数是错误的,headers 是分开的:

试试这个:

const axios = require("axios");
const fs = require("fs");
const FormData = require('form-data');

var fData = new FormData()
selectedFile = fs.createReadStream("./1653671203458audio.wav")

fData.append("file", selectedFile);
axios.post("http://127.0.0.1:5000/upload",
  fData,
{
  headers: {
    ...fData.getHeaders(),
  }
}).then(function (response) {
  console.log(response.data);
}).catch(function(response){
  console.log(response);
});