@Sherbadshah After days of trying to figure this out myself, I ended up sending my form data separate from my image. I created two services. The first SubmitForms service actually calls the PhotoUpload service and receives a response back of success or fail, and then sends the form data only if the photo successfully uploaded or if there is no photo attached. The SubmitForms service returns a promise back to the controller with success or fail.
.factory('SubmitForms', ['$http', '$q', 'PhotoUpload', 'URLS', function ($http, $q, PhotoUpload, URLS) {
return {
submit: function (formData) {
var q = $q.defer();
alert("FormData: " + JSON.stringify(formData));
if (formData.imageURI) {
PhotoUpload.upload(formData.imageURI, formData.imageName).then(function (response) {
console.log('PhotoUpload response: ' + response);
if (response == "Success") {
submitFormData();
} else {
q.reject(response);
}
}, function (err) {
console.log('PhotoUpload error: ' + err);
q.reject(err);
});
} else {
submitFormData();
}
function submitFormData() {
$http({
url: URLS.baseURL + URLS.submitForms, //enter your url for submitting form data
method: 'POST',
data: formData,
headers: {
'Content-Type': 'application/json'
},
config: {
timeout: 10000
}
})
.then(function (response) {
//console.log(response.data);
if (response.data.error.code == '000') {
q.resolve(response);
} else {
q.reject(response);
}
}, function (error) {
console.log("Server Error: " + JSON.stringify(error));
q.reject(error);
});
}
return q.promise;
},
getFileType: function (imgURI) {
var fileType = imgURI.substr(imgURI.lastIndexOf('.'), 4);
if (fileType == '.jpe') {
fileType = '.jpeg';
}
return fileType;
}
};
}]) // ********** end Submit Forms factory **********
.factory('PhotoUpload', ['$q', 'URLS', function ($q, URLS) {
return {
upload: function (imgURI, fileName) {
var q = $q.defer();
function win(r) {
q.resolve(r.response);
}
function fail(e) {
q.reject(e);
}
var uri = encodeURI(URLS.baseURL + URLS.photoUpload); //enter your url for uploading photo
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileName;
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(imgURI, uri, win, fail, options);
return q.promise;
}
};
}]) // ********** end PhotoUpload factory **********
Simple php image upload
<?php
$tmp_name = $_FILES["file"]["tmp_name"];
$name = basename($_FILES["file"]["name"]);
$dest_img = "../img-uploads/images/".$name;
$f_path_info = pathinfo($name);
$file_ext = strtolower($f_path_info['extension']);
/* if its not an image return false */
if (in_array($file_ext,array('gif','jpg','png','jpeg'))) {
if (move_uploaded_file($tmp_name, $dest_img)) {
// success
echo "Success";
} else {
echo "Error: Failure uploading image!";
//return error
}
} else {
echo "Error: Not an image file!";
}
?>
Hope that helps. Good Luck,
RGecy