Skip to content

Instantly share code, notes, and snippets.

@fisshy
Last active October 9, 2016 17:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fisshy/f7903a5ac8a9c7cf5c49 to your computer and use it in GitHub Desktop.
Save fisshy/f7903a5ac8a9c7cf5c49 to your computer and use it in GitHub Desktop.
Simple image upload to image-shack using node.js
Request your API key here
http://imageshack.us/api_request/
For more information please visist
https://docs.google.com/document/d/16M3qaw27vgwuwXqExo0aIC0nni42OOuWu_OGvpYl7dE/pub
var request = require("request");
var fs = require('fs');
var FormData = require('form-data');
function ImageShack (apiKey, persist) {
this.apiKey = apiKey;
this.persist = persist;
this.authToken = process.env.IMG_AUTHTOKEN
};
ImageShack.prototype.login = function (username, password, next) {
if(this.authToken) { return next(); }
var self = this;
var r = request.post('https://api.imageshack.com/v2/user/login',
function (err, httpResponse, body) {
if (err) { next(err); }
var result = JSON.parse(body);
console.log(result);
if(self.persist) {
self.authToken = process.env.IMG_AUTHTOKEN = result.result.auth_token;
}
next(null, result);
});
var form = r.form();
form.append('email', username);
form.append('password', password);
form.append('api_key', this.apiKey);
};
ImageShack.prototype.upload = function (sourcePath, next) {
console.log(sourcePath);
var form = new FormData();
form.append('file', fs.createReadStream(sourcePath));
form.append('api_key', this.apiKey);
form.append('auth_token', this.authToken);
form.getLength(function(err,length){
var r = request.post('https://api.imageshack.com/v2/images', {
headers: { 'content-length': length }
},
function(err, res, body) {
var result = JSON.parse(body);
console.log(result);
return next(err, result);
});
r._form = form;
});
};
module.exports = ImageShack;
var ImageShack = require('./image-shack');
function upload(imagePath, next) {
var imageShack = new ImageShack(apiKey, true);
imageShack.login(username, password,
function(err, result) {
if(err) { return next(err); }
imageShack.upload(imagePath, function(err, result) {
if(err) { return next(err); }
if(!result.success) { return next('failed'); }
return next(null, result.result.images[0].direct_link);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment