Skip to content

Instantly share code, notes, and snippets.

@fesor
Created January 19, 2015 08:25
Show Gist options
  • Save fesor/20d35041c14faacaccaa to your computer and use it in GitHub Desktop.
Save fesor/20d35041c14faacaccaa to your computer and use it in GitHub Desktop.
Cordova: FormData file upload
function upload (url, files, config) {
config = config || {};
files = angular.isArray(files) ? files : [files];
config.transformRequest = angular.identity;
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
return fileAppender(files).then(function (formData) {
return $http.post(url, formData, config);
}, repeatRejection);
};
function fileAppenderFactory ($q, $window, $log, safeApply) {
var mimetypes = {
// only for example
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png'
};
return function (files, formData) {
formData = formData || new FormData();
var fileID = 0;
return $q.all(files.map(function (fileUri) {
return addFile(formData, fileUri, 'file' + fileID++);
})).then(function () {
return formData;
}, function (reason) {
return $q.reject(reason);
})
};
function addFile(form, fileUri, key) {
$log.debug('Add file: %s', fileUri);
var deferred = $q.defer();
$window.resolveLocalFileSystemURL(fileUri, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (fileReadResult) {
var data = new Uint8Array(fileReadResult.target.result);
var blob = createBlob(data, file.type || getMimeType(file.name));
form.append(key, blob, file.name);
safeApply(function () {
deferred.resolve();
});
};
reader.onerror = function (fileReadResult) {
safeApply(function () {
deferred.reject(fileReadResult);
});
};
reader.readAsArrayBuffer(file);
});
});
return deferred.promise;
}
function createBlob(data, type) {
var r;
try {
r = new $window.Blob([data], {type: type});
}
catch (e) {
// TypeError old chrome and FF
$window.BlobBuilder = $window.BlobBuilder ||
$window.WebKitBlobBuilder ||
$window.MozBlobBuilder ||
$window.MSBlobBuilder;
// consider to use crosswalk for android
if (e.name === 'TypeError' && window.BlobBuilder) {
var bb = new BlobBuilder();
bb.append([data.buffer]);
r = bb.getBlob(type);
}
else if (e.name == "InvalidStateError") {
// InvalidStateError (tested on FF13 WinXP)
r = new $window.Blob([data.buffer], {type: type});
}
else {
throw e;
}
}
return r;
}
function getMimeType(fileName) {
var extension = fileName.split('.').pop();
return mimetypes.hasOwnProperty(extension) ?
mimetypes[extension] : undefined;
}
}
@kylethielk
Copy link

Thank you, very very much! Was looking all over for this for a while!

@jyoansah
Copy link

jyoansah commented Oct 5, 2017

This is awesome! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment