Skip to content

Commit

Permalink
Merge pull request #25 from conord33/feature/autodocs/fileupload
Browse files Browse the repository at this point in the history
Feature/autodocs/fileupload
  • Loading branch information
ppatriotis committed Dec 12, 2013
2 parents 0be2589 + 260e906 commit b30ba38
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 6 deletions.
73 changes: 71 additions & 2 deletions autodocs/iodocs/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ function processRequest(req, res, next) {
};

var reqQuery = req.body,
reqFiles = req.files,
customHeaders = {},
params = reqQuery.params || {},
locations = reqQuery.locations || {},
Expand Down Expand Up @@ -306,7 +307,17 @@ function processRequest(req, res, next) {
};

if (['POST','DELETE','PUT'].indexOf(httpMethod) !== -1) {
if(config.jsonRequests) {
if(reqFiles) {
var files2Post = {};
for (var file in reqFiles.params) {
if (reqFiles.params.hasOwnProperty(file))
files2Post[file] = reqFiles.params[file];
}
var headersAndParams = getFormDataForPost(params, files2Post);
for (var key in headersAndParams.headers) options.headers[key] = headersAndParams.headers[key];
requestBody = headersAndParams.postdata;
}
else if(config.jsonRequests) {
// Extract body param if it's a json request, and just use it as the post body
for( var param in params )
{
Expand Down Expand Up @@ -607,7 +618,11 @@ function processRequest(req, res, next) {
};
});

if (requestBody) {
if (requestBody instanceof Array) {
for (var i = 0; i < requestBody.length; i++)apiCall.write(requestBody[i]);
apiCall.end();
}
else if (requestBody) {
apiCall.end(requestBody, 'utf-8');
}
else {
Expand Down Expand Up @@ -712,3 +727,57 @@ if (!module.parent) {
console.log("Express server listening on port %d", app.address().port);
});
}

/**
Converts a list of parameters to forum data
- `fields` - a property map of key value pairs
- `files` - a list of property maps of content
- `type` - the type of file data
- `keyname` - the name of the key corresponding to the file
- `valuename` - the name of the value corresponding to the file
- `data` - the data of the file
*/
function getFormDataForPost(fields, files) {
function encodeFieldPart(boundary,name,value) {
var return_part = "--" + boundary + "\r\n";
return_part += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n";
return_part += value + "\r\n";
return return_part;
}
function encodeFilePart(boundary,type,name,filename) {
var return_part = "--" + boundary + "\r\n";
return_part += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"\r\n";
return_part += "Content-Type: " + type + "\r\n\r\n";
return return_part;
}
var boundary = '----------------------------' + (Math.ceil(Math.random() * 17592186044416 + 263882790666239).toString(16));
var post_data = [];

if (fields) {
for (var key in fields) {
var value = fields[key];
post_data.push(new Buffer(encodeFieldPart(boundary, key, value), 'ascii'));
}
}
if (files) {
for (var key in files) {
var value = files[key];
post_data.push(new Buffer(encodeFilePart(boundary, value.type, key, value.name), 'ascii'));
post_data.push(fs.readFileSync(value.path));
}
}
post_data.push(new Buffer("\r\n--" + boundary + "--"), 'ascii');
var length = 0;

for(var i = 0; i < post_data.length; i++) {
length += post_data[i].length;
}
var params = {
postdata : post_data,
headers : {
'Content-Type': 'multipart/form-data; boundary=' + boundary,
'Content-Length': length
}
};
return params;
}
29 changes: 26 additions & 3 deletions autodocs/iodocs/public/javascripts/docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,14 @@
apiSecret = { name: 'apiSecret', value: $('input[name=secret]').val() },
apiName = { name: 'apiName', value: $('input[name=apiName]').val() };

var inputFiles = false;
if ($(this).find('.file2upload').length > 0) {
inputFiles = new FormData();
$(this).find('.file2upload').each(function(i, el) {
inputFiles.append($(el)[0].name, $(el)[0].files[0]);
});
}

params.push(apiKey, apiSecret, apiName);

// Setup results container
Expand Down Expand Up @@ -238,9 +246,25 @@
.addClass('response prettyprint'));
}

console.log(params);
var ajaxOptions = {
url: basePath + 'processReq',
type: 'POST'
};

if (inputFiles) {
params.forEach(function(param) {
inputFiles.append(param['name'], param['value'])
});
ajaxOptions['processData'] = false;
ajaxOptions['contentType'] = false;
ajaxOptions['data'] = inputFiles;
} else {
ajaxOptions['data'] = params;
}


$.post(basePath + 'processReq', params, function(result, text) {
$.ajax(ajaxOptions)
.success(function(result, text) {
// If we get passed a signin property, open a window to allow the user to signin/link their account
if (result.signin) {
window.open(result.signin,"_blank","height=900,width=800,menubar=0,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0");
Expand All @@ -254,7 +278,6 @@
.toggleClass('error', false)
.text(formatJSON(JSON.parse(response)));
}

})
// Complete, runs on error and success
.complete(function(result, text) {
Expand Down
2 changes: 2 additions & 0 deletions autodocs/iodocs/views/api.jade
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ ul
option(value=choice, selected=true) #{choice}
- else
option(value=choice) #{choice}
- else if (parameter.Type =='file')
input(class='file2upload', type='file', name='params[' + parameter.Name + ']', multiple='multiple')
- else
- if (parameter.Location == 'body' && config.jsonRequests)
textarea(name='params[' + parameter.Name + ']', value=parameter.Default, placeholder=className, rows=8, columns=6)
Expand Down
2 changes: 1 addition & 1 deletion extensions/Identity/models/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class Session extends Model {
* so that an extra request does not need to be made to the User controller. This is most likely wasteful for other
* requests so only the userId field is filled.
*
* @var User
* @var \MABI\Identity\User
* @field external
*/
public $user;
Expand Down

0 comments on commit b30ba38

Please sign in to comment.