Jerald
Jerald

Reputation: 4048

How to send multipart/form-data PUT request in NodeJs?

I need to send an array like this:

[
  a: 'b',
  file: {file content}
]

I tried to do it using request module with formData option:

request.put({
  url: 'http://example.com/upload',
  formData: {
    a: 'b',
    file: fs.createReadStream(__dirname + '/for-test.jpg')
  }
});

In this example PUT data will be empty, it seems like formData option is ignored.

Upvotes: 2

Views: 4781

Answers (2)

mattr
mattr

Reputation: 5518

I tried out your code and had the same problem. After some digging i realized you are using an unreleased feature.

If you search the current npm package for the string 'formData', it doesn't exist. If you clone the latest on github, and search that, the string 'formData' appears (I did a search using grep, btw) and there is even a test for it.

If you want to use this feature prerelease you can just hook up your package.json to point to the repo:

{
  ...
  "dependencies": {
    ...
    "request":"git+https://github.com/request/request.git#master",
    ...
  }
} 

A fresh npm install will give you the latest from github with that feature. After doing that everything was fixed for me.

that should hold you over until the feature is released :)

Upvotes: 2

T.W.R. Cole
T.W.R. Cole

Reputation: 4156

You need to use the body attribute, and you need to stringify your object.

request({
    method: 'PUT',
    url: 'http://example.com/upload',
    body: JSON.stringify({
        a: 'b',
        file: fs.createReadStream(__dirname + '/for-test.jpg')
    })
});

Upvotes: 2

Related Questions