H
H
hodik2014-01-07 02:12:17
JavaScript
hodik, 2014-01-07 02:12:17

How to implement loading binary files from node.js?

I'm trying to implement uploading photos on VKontakte with download proxying through a node.js server.
External packages are used:
node-vkontakte - access to VKontakte API
q - promise implementation
node-form-data - FormData
implementation I'm trying to load a test . jpg image but keep getting a Security Breach2 error at the address from uploadUrl .
Code example:

app.post '/api/vk/upload', (req, res) ->
  albumId = parseInt(req.query.albumId)
  groupId = parseInt(req.query.groupId)

  image = new Buffer(req.body.image)
  vk = vkontakte(config.vk.accessToken)
  q.nfcall(vk, 'photos.getUploadServer', 
    aid: albumId
  )
  .then (response) ->
      deferred = q.defer()
      // адрес для загрузки изображения
      uploadUrl = response.upload_url

      form = new FormData()
      form.append 'file1', image,
        contentType: 'image/jpg',
        filename: '1.jpg'

      request = form.submit uploadUrl

      request.on 'response', (_response) ->

        parts = []
        _response.on 'data', (c) ->
          parts.push(c)

        _response.on 'end', () ->
          // parts.join('') === 'Security Breach2'
          console.log parts.join('')
          deferred.resolve JSON.parse(parts.join(''))

      request.on 'error', (error) ->
        deferred.reject(error)

      return deferred.promise

    ,(reason) ->
      res.json
        error: reason.error_msg
  .then (response) ->
    res.json response

  .catch (error) ->
    res.json
      error: error.message

  .done()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
7
75bytes, 2014-02-11
@75bytes

Try the restler module . Perhaps I somehow used the rest in a wrong way (including node-form-data, and node-curl, and native http.request), but it was restler that worked for me. Here is the request:

var rest = require('restler');
....
rest.post(data.upload_url, {
    multipart: true,
    data: {
      'file1': rest.file(__dirname  + '/test.png', null, fs.statSync(__dirname  + '/test.png').size, null, 'image/png')
    }
  }).on('complete', function(data) {
      console.log('restler', data);
      res.send(data);
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question