最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node.js multipartform-data local file upload to api - Stack Overflow

programmeradmin5浏览0评论

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 ing 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.

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 ing 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.

Share Improve this question edited Oct 19, 2016 at 12:41 Kristian Tang asked Oct 19, 2016 at 12:11 Kristian TangKristian Tang 451 gold badge1 silver badge8 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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);
  }
);
发布评论

评论列表(0)

  1. 暂无评论