From 2f4d0b8b45dbb766a3348200fdff02ee00d9d6c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niklas=20Na=CC=88rhinen?= Date: Thu, 23 Oct 2014 01:49:25 +0300 Subject: [PATCH] Automatic Content-Type for FormData uploads When data passed to axios is of type FormData we have to let the browser create the Content-Type header so that the boundaries will get right etc. Usage: ```js var data = new FormData(); data.append('field', 'some string'); data.append('file', someFile); var opts = { transformRequest: function(data) { return data; } }; axios.post('/fileupload', data, opts); ``` --- lib/adapters/xhr.js | 4 ++++ lib/utils.js | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/adapters/xhr.js b/lib/adapters/xhr.js index 70a6e9f..f44bd45 100644 --- a/lib/adapters/xhr.js +++ b/lib/adapters/xhr.js @@ -21,6 +21,10 @@ module.exports = function xhrAdapter(resolve, reject, config) { config.headers || {} ); + if (utils.isFormData(data)) { + delete headers['Content-Type']; // Let the browser set it + } + // Create the request var request = new(XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP'); request.open(config.method, buildUrl(config.url, config.params), true); diff --git a/lib/utils.js b/lib/utils.js index 516ff6f..6bd0338 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -22,6 +22,16 @@ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } +/** + * Determine if a value is a FormData + * + * @param {Object} val The value to test + * @returns {boolean} True if value is an FormData, otherwise false + */ +function isFormData(val) { + return toString.call(val) === '[object FormData]'; +} + /** * Determine if a value is a view on an ArrayBuffer * @@ -188,6 +198,7 @@ function merge(obj1/*, obj2, obj3, ...*/) { module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, + isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber,