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

Time:05-31

I have the following command that works in uploading a .wav file

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

the relevant code on the server side is the following, using 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"

I've tried many things to try and have it uploaded the same way in nodejs without success, the follwing is the latest and it returns "no file was sent"

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);
});

CodePudding user response:

check axios example

so file=@./1653671203458audio.wav should be fData.append("file", selectedFile); also, axios post arguments are wrong, headers are separated:

try this:

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);
});
  • Related