Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for proper onprogress events for file uploads #20

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ Parameters:
+ string (sets content type to 'application/x-www-form-urlencoded' if not set in headers)
+ FormData (doesn't set content type so that browser will set as appropriate)
- `method`: 'GET', 'POST', etc. Defaults to 'GET' or 'POST' based on body
- `onprogress`: function callback, will be called multiple times with a progress event when uploading files using FormData
- `cors`: If your using cross-origin, you will need this true for IE8-9 (to use the XDomainRequest object, also see [Compatibility](#compatibility))

The following parameters are passed directly onto the request object:
Expand Down
9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,13 @@ exports.ajax = function (params, callback) {

for (var i = 0, len = reqfields.length, field; i < len; i++) {
field = reqfields[i]
if (params[field] !== undefined)
req[field] = params[field]
if (params[field] !== undefined){
if(body && global.FormData && body instanceof global.FormData && field == 'onprogress'){
req.upload[field] = params[field];
}else{
req[field] = params[field];
}
}
}

for (var field in headers)
Expand Down
2 changes: 1 addition & 1 deletion nanoajax.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,28 @@ function defineTests(ajax) {
done()
})
})

test('FormData progress', function(done){
var formData = new FormData();
formData.append("arg", "value");
formData.append("foo", "bar");

var isLengthComputable = false;

var progressHandler = function(e){
isLengthComputable = e.lengthComputable;
}

ajax({url: '/post',
body: formData,
method: 'POST',
onprogress: progressHandler
}, function (code, body) {
assert.equal(isLengthComputable, true)
done()
})

})
}

// Safari:
Expand Down