Skip to content

Commit

Permalink
Merge pull request #43 from abrom/master
Browse files Browse the repository at this point in the history
Extended built in uploadFile function
  • Loading branch information
Rovak committed Oct 25, 2014
2 parents 49262cf + c21c992 commit bdfe96c
Showing 1 changed file with 36 additions and 3 deletions.
39 changes: 36 additions & 3 deletions src/inline-attach.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@
extension = fileNameMatches[1];
}
}
formData.append(settings.uploadFieldName, file, "image-" + Date.now() + "." + extension);
if (settings.addFileBeforeExtraParameters) {
formData.append(settings.uploadFieldName, file, "image-" + Date.now() + "." + extension);
}


// Add any available extra parameters
if (typeof settings.extraParams === "object") {
Expand All @@ -66,7 +69,12 @@
}
}

xhr.open('POST', settings.uploadUrl);
// Add the file after the extra parameters
if (!settings.addFileBeforeExtraParameters) {
formData.append(settings.uploadFieldName, file, "image-" + Date.now() + "." + extension);
}

xhr.open(settings.uploadMethod, settings.uploadUrl);

// Add any available extra headers
if (typeof settings.extraHeaders === "object") {
Expand All @@ -80,7 +88,7 @@
xhr.onload = function() {
// If HTTP status is OK or Created
if (xhr.status === 200 || xhr.status === 201) {
var data = JSON.parse(xhr.responseText);
var data = me.parseResponse(xhr);
me.onUploadedFile(data);
} else {
me.onErrorUploading();
Expand All @@ -89,6 +97,10 @@
xhr.send(formData);
};

this.parseResponse = function(xhr) {
return settings.customResponseParser.call(this, xhr) || JSON.parse(xhr.responseText);
};

/**
* Check if the given file is allowed
*
Expand Down Expand Up @@ -247,11 +259,22 @@
*/
uploadUrl: 'upload_attachment.php',

/**
* Upload HTTP method used
*/
uploadMethod: 'POST',

/**
* Request field name where the attachment will be placed in the form data
*/
uploadFieldName: 'file',

/**
* Add the file to the form data before adding the extra parameters
* (alternative being to add the file after the extra parameters)
*/
addFileBeforeExtraParameters: true,

/**
* Where is the filename placed in the response
*/
Expand Down Expand Up @@ -318,6 +341,16 @@
return true;
},

/**
* Custom response parser
*
* @return {Object} containing a parsed version of the response
* or a falsey value will default back to parsing the response as JSON
*/
customResponseParser: function(xhr) { // jshint unused:false
return null;
},

/**
* When a file has succesfully been uploaded
*/
Expand Down

0 comments on commit bdfe96c

Please sign in to comment.