0

我正在尝试使用 nodejs 将视频上传到 vimeo(https://developer.vimeo.com/apis/advanced/upload在第 3 步)。这是我目前所做的:

首先我调用函数来读取文件:

var options = {
         hostname : dataObject.ticket.host,
         path : '/upload?ticket_id=' + dataObject.ticket.id,
         port : 8080,
         method: 'POST'
       }

postMovie(options);

我从我的对象中获取这些参数:

{
    "generated_in": "0.0308",
    "stat": "ok",
    "ticket": {
        "endpoint": "http://126535.cloud.vimeo.com:8080/upload?ticket_id=9d818e8bd066dfd54e53f1be2fa3f958",
        "endpoint_secure": "https://126535.cloud.vimeo.com/upload?ticket_id=9d818e8bd066dfd54e53f1be2fa3f958",
        "host": "126535.cloud.vimeo.com",
        "id": "9d818e8bd066dfd54e53f1be2fa3f958",
        "max_file_size": "26843545600"
    }
}

这个函数被称为:

function postMovie(options){
    // This is an async file read
    fs.readFile('public/uploads/4363066343.mp4', function (err, data) {
      if (err) {

        console.log("FATAL An error occurred trying to read in the file: " + err);
        process.exit(-2);
      }
      // Make sure there's data before we post it
      if(data) {
        PostData(data,options);
      }
      else {
        console.log("No data to post");
        process.exit(-1);
      }
    });
};

读取文件时:

function PostData(data,options) {

      var headers = {
          'Content-Type': 'video/mp4',
          'Content-Length': data.length
      }

      options.headers = headers

      console.log(options)

  // Set up the request
  var post_req = http.request(options, function(res) {
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });

  // post the data
  post_req.write(data);
  post_req.end();

  post_req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
  });
}

我的 post_req.on(error) 记录了这个:

problem with request: write EPIPE
problem with request: write EPIPE

我知道这是因为服务器端超时。

我认为我的请求格式不正确。

有人能指出我做错了什么吗?

4

1 回答 1

0

使用请求模块,上传操作会简单得多。

var inspect = require('eyespect').inspector();
var request = require('request')
var path = require('path')
var fs = require('fs')
var filePath = path.join(__dirname, '../public/uploads/foo.mp4')
fs.stat(filePath, function(err, stats) {
  if (err) {
    inspect(err, 'error stating file')
    return
  }
  var fileSize = stats.size
  var url = 'https://126535.cloud.vimeo.com/upload?ticket_id=9d818e8bd066dfd54e53f1be2fa3f958'
  var opts = {
    url: url,
    method: 'post',
    headers: {
      'Content-Length': fileSize,
      'Content-Type': 'foo'
  }
  var r = request(opts)

  // pipe the file on disk to vimeo
  var readStream = fs.createReadStream(filePath)
  readStream.pipe(r)
  readStream.on('error', function (err) {
    inspect(err, 'error uploading file')
  })
  readStream.on('end', function (err) {
    inspect('file uploaded correctly')
  })
})

Request 还允许您设置timeout选项,如果文件很大,因此需要很长时间才能上传

于 2013-04-29T14:16:47.493 回答