0
votes

I need to issue a POST request in Node.js to an API which takes two parameters: 1) "metadata", a string, and 2) "file", a multipart file.

The following is part of the server-side java code:

public ResponseEntity<CmisDocumentDTO> createDocument(
        @ApiParam(name = "file", value = "File to be uploaded.", required = true) @RequestParam("file") MultipartFile file,
        @ApiParam(name = "metadata", value = "Metadata of the document", required = false) @RequestParam("metadata") String metadata) {
    //Calls the service
}

The following is my node.js code calling this request. The file is on my local machine and uses the form-data module:

var FormData = require('form-data');
var form = new FormData();
form.append("metadata", "metadata_string_goes_here");
form.append("file", fs.createReadStream(fileName));

var request = https.request({
    method: 'post',
    host: 'example.org',
    path: '/upload',
    "rejectUnauthorized": false,
    headers: form.getHeaders()
});

form.pipe(request);

request.on('response', function(res) {
    console.log(res.statusCode);
});

When I run this code, an internal service error (code: 500) is returned that says the MultipartFile parameter "file" is not present.

How do I successfully submit a POST request with a multipart file as a parameter?

Thanks!

1

1 Answers

0
votes

fileName should be path of the file in local machine

 fs.createReadStream(fileName)

In case you have not given absolute path starting with root then Relative paths work, but they are relative to process.cwd(), not the currently executing module.