upload-image.js 1010 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. var needle = require('../'),
  2. path = require('path');
  3. var image = 'https://upload.wikimedia.org/wikipedia/commons/a/af/Tux.png';
  4. function upload(obj, cb) {
  5. console.log('Uploading image...');
  6. var url = 'http://deviantsart.com';
  7. var opts = {
  8. timeout: 10000,
  9. follow: 3,
  10. multipart: true
  11. };
  12. var params = {
  13. file: obj
  14. }
  15. needle.post(url, params, opts, function(err, resp) {
  16. if (err || !resp.body.match('url'))
  17. return cb(err || new Error('No image URL found.'))
  18. cb(null, JSON.parse(resp.body).url)
  19. })
  20. }
  21. function download(url, cb) {
  22. console.log('Getting ' + url);
  23. needle.get(url, function(err, resp) {
  24. if (err) throw err;
  25. cb(null, resp.body);
  26. })
  27. }
  28. ////////////////////////////////////////
  29. // ok, now go.
  30. download(image, function(err, buffer) {
  31. if (err) throw err;
  32. var obj = { buffer: buffer, content_type: 'image/png' };
  33. upload(obj, function(err, url) {
  34. if (err) throw err;
  35. console.log('Image uploaded to ' + url);
  36. })
  37. })