1

I want to upload a file to a restful api service from my javascript application. It should use a local path like "c:/folder/test.png" and upload to something like "localhost/uploads", is there a easy approch, I am a little lost coming to the upload part and have tryed searching around, but didn't find any that matched my case, and I have tryed this code below:

    var request = require('request');

    var url = "http://localhost/uploads";
    var req = request.post(url, function (err, resp, body) {
          if (err) {
            console.log('Error!');
          } else {
            console.log('URL: ' + body);
          }
        });

    var form = req.form();

    form.append('file', fs.createReadStream("C:/kristian/Devbeasts-small.png"));

this code gives me the error: Error: Cannot find module 'request'

It requires a multipart form-data.

1 Answer 1

2

The post method can take an object containing an url and a formData object as first parameter, as seen here.

var formData = {
  name: 'file1',
  file: {
    value:  fs.createReadStream('C:/kristian/Devbeasts-small.png'),
    options: {
      filename: 'Logo_flame.png',
      contentType: 'image/png'
    }
  }
};

request.post({url:'http://localhost/uploads', formData: formData}, 
  function cb(err, httpResponse, body) {
    if (err) {
      return console.error('upload failed:', err);
    }
    console.log('Upload successful!  Server responded with:', body);
  }
);
Sign up to request clarification or add additional context in comments.

10 Comments

When I use the request I get the error: Error: Cannot find module 'request'
Did you keep var request = require('request'); ? Make sure to run npm install request before running the script.
Is it possible to download the module manually and not with npm install?
isn't it possible to use http?
You can, but it's more complicated. nodejs.org/api/http.html#http_http_request_options_callback You should get used to npm for Node development, it's unnecessary difficult to create applications without it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.