简体   繁体   中英

How to upload assets to a github release from node.js

I am trying to automatically post some assets on a Github release I programmatically create.

Here is my upload function:

function uploadFile(fileName, uploadUrl, callback){

  var uploadEndPoint = url.parse(uploadUrl.substring(0,uploadUrl.indexOf('{')));

  options.host = uploadEndPoint.hostname;
  options.path = uploadEndPoint.pathname+'?name=' + fileName;
  options.method = 'POST';
  options.headers['content-type'] = 'application/zip';

  var uploadRequest = https.request(options, callback);

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

  var readStream = fs.ReadStream(path.resolve(__dirname,'builds',fileName));
  readStream.pipe(uploadRequest);

  readStream.on('close', function () {
    req.end();
    console.log('release.js - ' + fileName + ' sent to the server');
  });
}

At the end of this I get a 404 not found

I tried auth from token and user/password

I checked the url

I though it might be because of SNI, but I don't know how to check that.

Any clue ? Thanks !

I found a solution to that problem by NOT using the low level node.js modules and using instead restler which is a library that handles SNI.

Here is how is used it:

  rest = require('restler'),
  path = require('path'),
  fs = require('fs');

  fs.stat(path.resolve(__dirname,'builds',fileName), function(err, stats){
    rest.post(uploadEndPoint.href+'?name=' + fileName, {
      multipart: true,
      username: GITHUB_OAUTH_TOKEN,
      password: '',
      data: rest.file(path.resolve(__dirname,'builds',fileName), null, stats.size, null, 'application/zip')
    }).on('complete', callback);
  });

Hope that will help someone :)

EDIT on 27/02/2015: We recently switched from restler to request .

var 
 request  = require('request'),
 fs = require('fs');

var stats = fs.statSync(filePath);

var options = {
  url: upload_url.replace('{?name}', ''),
  port: 443,
  auth: {
    pass: 'x-oauth-basic',
    user: GITHUB_OAUTH_TOKEN
  },
  json:true,
  headers: {
    'User-Agent': 'Release-Agent',
    'Accept': 'application/vnd.github.v3+json',
    'Content-Type': 'application/zip',
    'Content-Length': stats.size
  },
  qs: {
    name: assetName
  }
};

// Better as a stream
fs.createReadStream(filePath).pipe(request.post(options, function(err, res){
  // Do whatever you will like with the result
}));

The upload_uri can be retrieved through a get request on an existing release or in the response directly after the release creation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM