1

I'm attempting to use the ng-file-upload directive to provide file upload functionality in my angular app.

I've got it working for the most part - I can select multiple files and loop through to grab the file name and file types. I just can't seem to figure out where the actual binary data of each file is stored in the file object.

I tried using the approach outlined in this post - AngularJS Upload a file and send it to a DB, but that results in a an error that "$q is not defined".

function create_blob(file) {
    var deferred = $q.defer();
    var reader = new FileReader();
    reader.onload = function () {
        deferred.resolve(reader.result);
    };
    reader.readAsDataURL(file);
    return deferred.promise;
}

So then I tried the approach outlined in this post - Send an uploaded image to the server and save it in the server, but again I'm running into an error reading "dataURI.split is not a function".

function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    var array = [];
    for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {
        type: mimeString
    });
}

The code I'm using is as follows:

function create_blob(file) {
    var deferred = $q.defer();
    var reader = new FileReader();
    reader.onload = function () {
        deferred.resolve(reader.result);
    };
    reader.readAsDataURL(file);
    return deferred.promise;
}

function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    var array = [];
    for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {
        type: mimeString
    });
}

$scope.uploadFiles = function (files) {
    $scope.files = files;
    angular.forEach(files, function (file) {
        if (file && !file.$error) {

            //var reader = new FileReader();
            //console.log(reader.readAsDataURL(file));

            //var binary = create_blob(file);
            var fileBinary = dataURItoBlob(file);

            $http({
                url: root + '/DesktopModules/ServiceProxy/API/NetSuite/InsertCaseFile',
                method: "POST",
                //headers: { 'caseId': id, 'fileName': file.name, fileContent: $.base64.encode(file) }
                headers: { 'caseId': id, 'fileName': file.name, fileContent: fileBinary }
            }).
            success(function (data, status, headers, config) {
                //if (data == true) {
                //    getCase();
                //    $scope.newMessage = "";
                //    //toaster.pop('success', "", "Message succesfully submitted.",0);
                //}
            }).
            error(function (data, status, headers, config) {
            });

            file.upload.progress(function (evt) {
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    });
}

What am I overlooking?

Community
  • 1
  • 1
GregVP
  • 73
  • 1
  • 6

1 Answers1

3

It depends on what format your DB is accepting for file upload. If it support multipart form data, then you can just use

Upload.upload({file: file, url: my/db/url}).then(...);

if it accepts post requests with file's binary as content of the request (like CouchDB, imgur, ...) then you can do

Upload.http({data: file, url: my/db/url, headers: {'Content-Type': file.type}})...;

if you db just accept json objects and you want to store the file as base64 data url in the database like this question then you can do

Upload.dataUrl(file, true).then(function(dataUrl) {
    $http.post(url, {
              fileBase64DataUrl: dataUrl, 
              fileName: file.name,
              id: uniqueId
    });
})
Community
  • 1
  • 1
danial
  • 4,058
  • 2
  • 32
  • 39
  • I'm trying to pass the file name, the binary data in base64 and a unique ID to a custom webservice. What is the most direct way to get that base64 string of the file binary content? – GregVP Sep 24 '15 at 15:08
  • Third approach. I edited the answer to show adding other fields. – danial Sep 24 '15 at 22:39