Skip to content

Instantly share code, notes, and snippets.

@sugumura
Last active March 20, 2016 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sugumura/23367272d2d2479f37c6 to your computer and use it in GitHub Desktop.
Save sugumura/23367272d2d2479f37c6 to your computer and use it in GitHub Desktop.
Cordova上でAngularJSから画像ををform-dataでPOSTする
/**
* require cordova-plugin-file ($cordovaFile)
*/
angular.module('app')
.factory('FileUploader', ['$q', '$http', '$cordovaFile',function ($q, $http, $cordovaFile) {
return {
fileUpload: function (path, fileName) {
var self = this;
var fd = new FormData();
return $q.resolve()
.then(function () {
return self.getPath(path, fileName)
})
.then(function (fileEntry) {
return self.getFile(fileEntry);
})
.then(function (file) {
return self.getFileReader(file);
})
.then(function (file) {
var imgBlob = new Blob([ file.result ], { type: "image/jpeg" } );
fd.append('image', imgBlob);
fd.append('file_name', fileName);
return $http.post(
'http://example.com/api/upload',
fd,
{
transformRequest: null,
headers: {'Content-type':undefined}
}
)
});
},
getPath: function (path, fileName) {
return $cordovaFile.checkFile(path, fileName);
},
getFile: function (fileEntry) {
var q = $q.defer();
try {
fileEntry.file(function (file) {
q.resolve(file);
})
} catch (err) {
q.reject(err);
}
return q.promise;
},
getFileReader: function (file) {
var q = $q.defer();
try {
var fr = new FileReader();
fr.onloadend = function () {
q.resolve(this);
};
fr.onerror = function () {
q.reject(this.error);
};
fr.readAsArrayBuffer(file);
} catch (err) {
q.reject(err);
}
return q.promise;
}
};
}])
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment